Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importance of css stylesheet hierarchy

Tags:

css

I've done some Google searches and so far I haven't found anything that answers my question about CSS order or importance.

For example, inline overrides external. Got it. Adding !important externally can override inline. Also, from everything I've ever been taught, later styles override earlier styles. So:

h1 { font-size: 12pt; }
h1 { font-size: 14pt; }

would render a font-size of 14pt. But this isn't always the case. Sometimes I want to define styles like:

<div id="content">
    <input class="regular" type="text" />
    <input class="regular" type="text" />
    <input class="long" type="text" />

and then in css:

#content input { width: 50%; }
.long { width: 75%; }

but that doesn't always work. Where can I see the order of importance because all of these have specific importance levels:

input {} 
#content input {}
#content input.regular {}
#content input.long
input.regular {}
input.long {}
.regular {}
.long {}

I really don't like having to write !important ever but if I can't figure out the order of importance specifically, then sometimes I have to change ids, classes, etc.

like image 275
o_O Avatar asked Jul 17 '12 19:07

o_O


1 Answers

The term you want to search for is “specificity”.

When you have two (or more) CSS blocks whose selectors select the same HTML element, and which both try to set the same CSS property on that element, then the block with the more specific selector wins out.

The CSS 3 selectors spec details how specificity should be calculated, and it’s reasonably readable:

  • http://www.w3.org/TR/css3-selectors/#specificity

There are also some good blog posts that describe the rules too:

  • http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
  • http://reference.sitepoint.com/css/specificity

(Note that when the two blocks have selectors with the same specificity, only then does the later block’s rule win out, as in your example with h1s. A rule in a block with a more specific selector will override a rule a later block with a less specific selector.)

like image 78
Paul D. Waite Avatar answered Oct 02 '22 17:10

Paul D. Waite