Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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

</div>

But this doesn't work! The blah's width till cancels out class "wider"'s with.

like image 408
TIMEX Avatar asked Jan 15 '11 21:01

TIMEX


2 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
like image 80
Alin Purcaru Avatar answered Oct 29 '22 22:10

Alin Purcaru


use #blah.wider instead to solve this

like image 33
Gerben Avatar answered Oct 29 '22 22:10

Gerben