Friday, August 24, 2012

A coherent way
to make your website faster is to make the client code you send to the browser
smaller. When looking to optimize your CSS files, one of the most influential
measures you can employ is to use each declaration just one time.

Using every
declaration just once means making strict use of selector grouping.

For example,
you can combine these rules:

h3
{color: #cdcdef ;} p
{color: #cdcdef ;}

into a single
rule:

h3,
p {color: #cdcdef;}

While this
simple example appears obvious, things are getting more interesting and harder
to compute when talking about complex style sheets. In our experience, using each
declaration just one time can reduce the CSS file size by 20-40% on average.

First, very long selectors can
render this method useless. Repeating selectors like html body
table tbody tr td p span.example in order to have unique declarations doesn't save
much file size. In fact, since "using each declaration just one time"
might mean a higher number of selectors, this could even result in a bigger
style sheet. Using more compact selectors would help, and would enhance
the readability of your stylesheet.

Second, be aware of CSS
regulations. When a user agent can't parse the selector, it must ignore the declaration block as well. If you run
into trouble with this, just bend the " each declaration just one
time " rule – and use it more than once.

Third and most importantly, keep the cascade in mind. No matter if you're sorting your style sheets in a convinced way or are
very tranquil about the order in which rules appear in your style sheets, using
each declaration just one time will make you change the order of the rules in
one way or another. This order, however, can be decisive for a browser to
decide which rule to apply. The easiest solution if you're running into any
issues with this is to make an exception as well and use the declaration in
question more than once