CSS selectors : should I minimise my use of the class attribute in the HTML or optimise the speed

Posted by Laurent Bourgault-Roy on Stack Overflow See other posts from Stack Overflow or by Laurent Bourgault-Roy
Published on 2010-05-11T14:01:12Z Indexed on 2010/05/11 14:04 UTC
Read the original article Hit count: 236

As I was working on a small website, I decided to use the PageSpeed extension to check if their was some improvement I could do to make the site load faster. However I was quite surprise when it told me that my use of CSS selector was "inefficient". I was always told that you should keep the usage of the class attribute in the HTML to a minimum, but if I understand correctly what PageSpeed tell me, it's much more efficient for the browser to match directly against a class name. It make sense to me, but it also mean that I need to put more CSS classes in my HTML. It also make my .css file a little harder to read.

I usually tend to mark my CSS like this :

#mainContent p.productDescription em.priceTag { ... }

Which make it easy to read : I know this will affect the main content and that it affect something in a paragraph tag (so I wont start to put all sort of layout code in it) that describe a product and its something that need emphasis. However it seem I should rewrite it as

.priceTag { ... }

Which remove all context information about the style. And if I want to use differently formatted price tag (for example, one in a list on the sidebar and one in a paragraph), I need to use something like that

.paragraphPriceTag { ... }
.listPriceTag { ... }

Which really annoy me since I seem to duplicate the semantic of the HTML in my classes. And that mean I can't put common style in an unqualified

.priceTag { ... }

and thus I need to replicate the style in both CSS rule, making it harder to make change. (Altough for that I could use multiple class selector, but IE6 dont support them)

I believe making code harder to read for the sake of speed has never been really considered a very good practice . Except where it is critical, of course. This is why people use PHP/Ruby/C# etc. instead of C/assembly to code their site. It's easier to write and debug. So I was wondering if I should stick with few CSS classes and complex selector or if I should go the optimisation route and remove my fancy CSS selectors for the sake of speed?

Does PageSpeed make over the top recommandation? On most modern computer, will it even make a difference?

© Stack Overflow or respective owner

Related posts about css-selectors

Related posts about best-practices