Which of the following is better code:
div#style1{
}
or
#style1{
}
Also, should the element type be specified for classes or not?
1 Answer 1
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.
-
\$\begingroup\$ How much of a difference in speed would it make? \$\endgroup\$hkk– hkk2013年10月12日 22:42:49 +00:00Commented 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– user191312013年10月12日 22:46:02 +00:00Commented 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– cimmanon2013年10月17日 15:53:13 +00:00Commented Oct 17, 2013 at 15:53