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 ;}
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.
Let's have a
look at another example:
h1,
h2, h3 { font-weight: normal; }
a strong { font-weight: normal !important; }
strong { font-style: italic; font-weight: normal; }
#nav { font-style: italic; }
.note { font-style: italic; }
a strong { font-weight: normal !important; }
strong { font-style: italic; font-weight: normal; }
#nav { font-style: italic; }
.note { font-style: italic; }
Applying the
"any declaration just once" rule here results in:
h1,
h2, h3, strong { font-weight: normal; }
a strong { font-weight: normal !important; }
strong, #nav, .note { font-style: italic; }
a strong { font-weight: normal !important; }
strong, #nav, .note { font-style: italic; }
Note that the !important declaration makes a difference.
There are some
things to keep in mind when applying this method:
- 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.
No comments:
Post a Comment