Some readers have asked to me what is the better way to organize a CSS file to optimize code readability and simplify code management.
Generally, I adopt just some simple rules and, it's my opinion, they are useful in order not to become crazy if you have to manage a CSS file for a page/site with a complex design. In this post, I discuss for simplicity a typical two columns fixed layout like this:
Step 1: redefine HTML elementsI think it's a good rule to redefine HTML elements (
body,
a,
form,
input...) in the first rows of your CSS files.
/* ------------------------------- */
/* HTML Elements
/* ------------------------------- */
html {font-family:arial, verdana, sans serif; font-size:13px;}
a:link, a:visited{color:#0033CC;}
a:hover{color:#003366;}
h1, h2, h3, h4, h5, h6,
form, input, text-area{
border:0; padding:0; margin:0;
font-family:arial, verdana, sans serif;}
h1{font-size:24px; color:#000000;}
h2{font-size:18px; color:#666666;}
...
Step 2: define page elementsIn order to improve code readability, I suggest to indent all elements but with some sagacities: if an element have just two-three attributes (for example
#navbar), you can use a single line to declare all properties, otherwise it's better to declare every single property in a new line (for example see
#navbar li a:link, #navbar li a:visited):
/* ------------------------------- *//* PAGE Elements/* ------------------------------- */#container{width:780px; margin:0 auto;}#topbar{width:auto; display:block; height:80px;}#navbar{width:auto; display:block; height:24px;}#navbar ul, #navbar ul li{padding:0; margin:0; list-style:none; float:left;}#navbar a{color:#FFFFFF; font-weight:bold;}
#navbar a:hover{background:#777777;}#navbar li a:link,#navbar li a:visited {background:#444444;
text-decoration:none;
height:24px;
line-height:24px;
display:inline;
float:left;
width:auto;
padding:0px 10px;}
#main{width:auto; display:block;}#column_left{width:560px; margin-right:20px; float:left;}
#column_right{width:200px; float:left;}
div.spacer{clear:both; height:10px; display:block;}
#footer{width:auto; display:block; height:24px;}
#footer a{color:#666666; text-decoration:underline;}
Step 3: define custom classIn the final section of your CSS files, you can define all other custom classes with the same rules I specified above:
/* ------------------------------- *//* OTHER Class/* ------------------------------- */.small{font-size:
11px;}.underline{text-decoration:
underline;}div.small-section{background:
#CCCCCC;}div.small-section a{color:#333333; font-weight:bold;}
...
How I said, these are only my personal suggestions and not true rules, but I think you can find them useful in order to deploy a more readable CSS file.