Home » Html » How do I make a class take precedence over an id?

How do I make a class take precedence over an id?

Posted by: admin January 2, 2018 Leave a comment

Questions:
<div id="normal" class="wider">

</div>

But this doesn’t work! The blah’s width till cancels out class “wider”‘s with.

Answers:

What you have there is a CSS specificity problem.

.wider has a specificity of 0,0,1,0 while #normal has 0,1,0,0. You can’t beat an ID with anything else than an ID (or inline definitions, but that is not the case here).

What I would recommend, if you cannot put the needed width declaration in the #normal selector, is to put it in #normal.wider or, if that either isn’t possible, have an identified container, say #container, as high in the hierarchy as possible (maybe an ID on the body?) and replace .wider with #container .wider. This new selector will have a specificity of 0,1,1,0 which is a bit higher than 0,1,0,0.

Using !important will work too, but it should be used only as a last resort.

Example:

<div id="container" class="wrapper">
    <div id="normal" class="wider">
</div>

For this HTML snippet some possible selectors in decreasing order of specificity would be:

CSS Selector         -> Specificity
---------------------------------------
#container #normal   -> 0,2,0,0
#container .wider    -> 0,1,1,0 // These two have the same specificity so
#normal.wider        -> 0,1,1,0 // the last declared value will be used
#normal              -> 0,1,0,0
.wrapper .wider      -> 0,0,2,0
.wider               -> 0,0,1,0

Questions:
Answers:

use #blah.wider instead to solve this

Questions:
Answers:

You can decorate attributes with !important to increase their…importance.

.wider
{
    width:9000px !important;
}

Questions:
Answers:

As people have already mentioned, an ID has a specificity of 100, whereas a class has only 10.

An alternative to answers suggested (that doesn’t use !important,) is to remove the property from #normal that’s conflicting (the width,) and apply it to a second class. So it’d look like:

#normal {
     padding : 0;
     margin : 0;
}

.normal {
     width : 400px;
}

.wider {
     width : 1000px;
}

Leaving your actual markup to be:

<div id="normal" class="normal"> 
</div>

where you want the ‘normal width,’ and:

<div id="normal" class="wider">
</div>

Where you want the extra wide element. You may have to go back through your pages that use #normal to add the .normal class, but this will fix your problem.

I also think Gerben’s answer works too–adds 10 more specificity to the ID property (totally 110,) which should override the #normal width property.

#normal.wider {
     1000px;
}

Questions:
Answers:

256 CSS Classes Can Override an #id: http://codepen.io/chriscoyier/pen/lzjqh

Alin Purcaru’s answer explains the basic rules of css precedence calculation. But the explanation of the implementation could be found at http://hackerne.ws/item?id=4388649