Skip to content Skip to sidebar Skip to footer

Css :: Difference Between .classname And Div.classname

I write a html element as below ::
Foo box
and write css like .box { width: 400px; height: 40px; color: red; text-align: cente

Solution 1:

The difference is that in the first class you tell that all element (div, p, span ...) with class box have that attribute. Like this:

<span class="box">test</span>
<div class="box">test</div>
<p class="box">test</p>

The second class means that only div with class box has that attribute

Only this elements get second class:

<div class="box">test</div>

The selector before the class specify which type of elements can take this class

Solution 2:

.box means any element having class box.

Example:

<divclass="box">...</div><sectionclass="box">...</section><spanclass="box">...</span>

div.box means only div element having class box.

Example:

<divclass="box">...</div>

Solution 3:

One very important difference between div.box and simply .box is in something called selector specificity. It is a set of rules which defines which selector gets more weight once the browser starts going through all the selectors that potentially have influence on a particular element.

What this means is easily demonstrated in the following example (DEMO)

We have a simple div containing some text.

<divclass="box">
    Zarro boogs found!
</div>

Now we add some CSS selectors to the example.

div.box {
    padding:0.8em;
    background: #bd0000;
    color: #fff;
}
.box {
    color: #bd0000;
}

One of the most basic rules of CSS is that selectors can be redefined in a way that whatever definition comes last and has influence on a particular element its the one that is going to be used (the sole exception being when using !important which always takes precedence).

Now in the above example redefining the .box class selector should actually hide the text but instead its still visible. How is that possible if we said that latter rules always take precedence? Its because the div.box rule has a higher specificity that .box since it actually gets points for containing both an element (div) and a class selector (.box) in its selector declaration (div.box).

Of course the div.box rule will be applied only on a div element but since class selectors are often reusable pieces of code there is plenty of situations when they are used on divs.

Although the rules in the official W3 specification are not that hard to understand they are sometimes pretty hard to remember. That's why I would like to recommend an excellent article on CSS selector specificity which can be found here.

In my opinion selector specificity is by far the most important thing to master when it comes to tracing inheritance problems with CSS stylesheets.

Post a Comment for "Css :: Difference Between .classname And Div.classname"