CSS optimization

News Feed

Mashing things together - CSS optimization

So you have started writing and writing and writing and the CSS file is getting very long. This is were CSS optimization comes in. Don't run away, it not going to be very hard, in fact it is very simple to do. You may have even guessed what the first one is.

/* Unoptimized */
body {
background-color : black ;
}
body {
font-size : 1.5em ;
}
/* Optimized */
body {
font-size : 1.5em ;
background-color : black ;
}

The second example is much better don't you think. You see in CSS ; signals the end of a rule so you can start another one. So you don't have to redeclare the selector each time. Very basic really.

I don't think you will have guessed this one, but it still very simple. This time we are going to combine selectors.

/* Unoptimized */
h1 {
margin : 10px ;
}
h2 {
margin : 10px ;
}
/* Optimized */
h1 ,
h2
{
margin : 10px ;
}

You can see here both the h1 and h2 headings have the same rules margin : 10px; so we can combine them separating the selector with a commer. You don't have to put them on a separate line, I just like doing so because it is easier to read. CSS ignores all "white splace", that is spaces, tabs and line breaks.

The last way you can optimize you CSS is CSS short hand. Again don't get scared this is very not that difficult. Let go back to our margin on the h1 heading, but this time we want to have a different margin on each side of the heading.

/* Unoptimized */
h1 {
margin-top : 10px ;
margin-right : 15px ;
margin-bottom : 10px ;
margin-left : 15px ;
}
/* Optimized */
h1 {
margin : 10px 15px 10px 15px ;
}
/* Or even */
h1 {
margin : 10px 15px ;
}
/* if all margins were to be 15px */
h1 {
margin : 15px ;
}

The first optimized example the width of the margin are done in this order top right bottom left, or as you would all know it clock wise. The second optimized example it (bottom top) (left right).

At our CSS cheat sheet all shorthand properties are listed as such, I recommend you read it.