Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's better in CSS: div.something or just .something

In CSS, when setting a style on a div (for example) is there any benefit in including the 'div' other than to give it more precision for matching. Is it faster for the browser to render perhaps?

ie Is:

div.something { font-size: 1em; }

better than

.something { font-size: 1em; }

for any other reason than to narrow it down to only divs?

(The reason I ask is that I recently happened across a prominent site that includes the 'div's but most tend to not bother)

UPDATE:

Thanks for all the answers. The conclusion is that speed is a factor but not noticeable so worth ignoring. And the consensus on the best practice is that including the tag is cleaner - general rule should be to keep the CSS as 'tight' as possible for the required style.

like image 976
Jo P Avatar asked Feb 17 '09 10:02

Jo P


4 Answers

Besides the different semantics of both selectors, read this: Speed of CSS

like image 122
Gumbo Avatar answered Oct 13 '22 08:10

Gumbo


if you want to use a class on more than just divs, you can just use a general class like

.something{}

but the more specific a class is, the more prominent it is, regardless of the order , i.e.:

#someID div.something { background: green; }
div.something { background: blue;}
.something { background: red; }

Since the first one is the most specific:

<div class="something"> this will be blue </div>
<div id="someID">
  <div class="something">
    this will be green
  </div>
</div>
<p class="something">this will be red</div>
like image 34
naspinski Avatar answered Oct 13 '22 09:10

naspinski


Adding the element selector (div) to the rule increases the specificity of the rule, making it more important than a generic class selector (.something)

It also makes your CSS more readable. If all your class selectors aren't prepend'ed with elements, it means your classes are ambigious, and could apply to any element. (This could be the intention, but more often it's not)

As stated above, there is a speed trade-off by using element names, but it's hardly noticeable.

like image 37
ndorfin Avatar answered Oct 13 '22 09:10

ndorfin


Well I think the only purpose is like you said "to narrow it down to only divs". So that <p class="something"> should behave the same or not as the div...

like image 31
Vinze Avatar answered Oct 13 '22 09:10

Vinze