0
\$\begingroup\$

Which of the following is better code:

div#style1{
}

or

#style1{
}

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

asked Oct 12, 2013 at 21:25
\$\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.

answered Oct 12, 2013 at 22:35
\$\endgroup\$
3
  • \$\begingroup\$ How much of a difference in speed would it make? \$\endgroup\$ 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\$ 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\$ Commented Oct 17, 2013 at 15:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.