CSS Structure Guide

Thought Process

Alright, I believe consistency is everything. In CSS this helps keep your CSS readable and can help prevent conflicting styles.

Everything can depend upon what exactly needs to be done for a particular project but I usually work with a broad to specific. A mentality that should be used in determining the rules in which one will use for defining actual rules.

Document Structure

Right now I am talking about structure within a stylesheet. So I test frequently and get base functionality in place first and get a broad spectrum of work done first and then go in and fine-tune my project.

So naturally page structure comes first in my styles (and I comment regularly when I reach a new section of my CSS). So often my first section of my stylesheet will always look similar to this:

/*--------- Page Structure -------------- */

body{
	...
}

#wrapper{
	...
}

#header{
	...
}

#content{
	...
}

Next will come as many broad spectrum elements that need styling if body #header or #content do not pick them up.  Common is setting an initial font-size and family in the body tag which will carry through to many page elements unless specificity is higher from the user agent.

/* ------------ Page Elements ----------*/

p{
	...
}

h1, h2{
	...
}

img{
	...
}

Alright so this should cover a very good portion of a design using these. Kudos to you if this is all you need; Clean, semantic and readable! However if this is all we ever needed to do web developers wouldn’t have much job security! So any section after these are special and additional styles.

/*--------- Header Styles ---------------*/

#header h1{
	...
}

#header a{
	...
}

/*--------- Nav Styles ---------------*/

#nav ul li{
	...
}

#nav a:link, #nav a:visited{
	...
}

#nav a:hover, #nav a:active{
	...
}

#nav a.current{
	...
}

/*---------- Content Styles --------------*/

#content h4{
	...
}

#content a.feature{
	...
}

#content hr{
	...
}

Style Declaration Structure

I like to also be consistent in my code-style for my actual rules, properties and values.
For  CSS rule with only one property I keep it on one line:

#content a{  ...  }

For multiple properties I tab out the properties and keep the closing } on a separate line:

#content a{
	...
}

Declaration Order

I also like to order the declarations of my properties. I think of it as maintaining similar structure as my whole CSS document so structure and then details. So I always do my box-model items first followed by position, background styling, fonts and any other special styles in that order. So a complex block could look like this:

#content {
	display:block;
	height:100px;
	width:200px;
	position:relative;
	top:100px;
	left:100px;
	background:url(‘images/image.png’) top right no-repeat;
	color:#333;
	font-family:sans-serif;
	font-size:1.2em
}