Search code examples
cssstandards

Reason for CSS property precedence?


I actually know how the browsers tend to render the following examples (results based on Opera 9.5 and Firefox 3.0), but I don't understand the reason behind them.

Take this example,

<style type="text/css">
#outer{color:red;}
.inner{color:blue;}
</style>

<div id="outer" class="outer">
    <div id="inner" class="inner">
        <span>testing</span>
    </div> 
</div>

The result is blue text.

However, now see this example,

<style type="text/css">
#outer span{color:red;}
.inner span{color:blue;}
</style>

<div id="outer" class="outer">
    <div id="inner" class="inner">
        <span>testing</span>
    </div> 
</div>

The text is now red.

Finally, try this,

<style type="text/css">
#outer span{color:red;}
#inner span{color:blue;}
</style>

<div id="outer" class="outer">
    <div id="inner" class="inner">
        <span>testing</span>
    </div> 
</div>

Once again we have blue text.

Is there a specific reason for this methodology?

(sorry about the unclear title, it's the best I could manage.)


Solution

  • In example 1 the span element is not directly targeted, so we must look into how CSS Inheritance is handled. Color is an inherited property so we need to look at the span's closest parent element to determine color. In your example 1 case, the class (.inner) has color blue defined and passes that inheritance down to the span.

    In example 2 the span element is directly targeted by both rules, so we must look into the CSS Cascade to determine which of the rules that targets the element is most specific. The rule with the ID selector wins.

    In example 3 we invoke the CSS Cascade rules once again and since both specificities are equal, last rule wins.

    Note that in this situation:

     #outer {color: red; }
     span {color: blue; }
    

    The text will be blue. This is because the second rule targets the element directly and therefore does not invoke the CSS Cascade.

    More Reading:

    Note and Disclosure: I authored the third blog post.