0
\$\begingroup\$

Which of the following is better code:

div#style1{

}

or

#style1{
}

Also, should the element type be specified for classes or not?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

It depends what you mean by "better".

Because of the way the style system matches rules, #style1 is faster than div#style1 (and the same goes for classes). For this reason, conventional wisdom is that the former, less-qualified selector is better.

However, it may be that div#style1 is more easily understood by the next person1 editing the CSS than #style1 (in the specific case you give, probably not - but, for example, the meaning of a selector like a.external is immediately obvious to anyone reading it in a way that a bare .external isn't).

In cases like that, you have to decide which is more important: making your CSS as straightforward as possible to maintain, or making it (perhaps only very slightly) faster to render.


1 Maybe you in eighteen months, maybe someone else entirely.

\$\endgroup\$
3
  • \$\begingroup\$ How much of a difference in speed would it make? \$\endgroup\$
    – hkk
    Commented Oct 12, 2013 at 22:42
  • 1
    \$\begingroup\$ @cloudcoder2000 that's going to depend on your specific code - if rendering speed is an issue, test it; if not, don't waste time worrying about it. \$\endgroup\$
    – user19131
    Commented Oct 12, 2013 at 22:46
  • 2
    \$\begingroup\$ The performance penalty for anything other than class or id is almost always greatly exaggerated: stevesouders.com/blog/2009/03/10/… \$\endgroup\$
    – cimmanon
    Commented Oct 17, 2013 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.