Search code examples
htmlcsscss-selectorscss-specificity

CSS specificity precedence


I am getting red background-color for both h1. For the first h1, ID has the highest precedence and for the second h1, the inline has the highest precedence. Why?

#myid      { background-color: pink; }
.main h1   { background-color: red; }
div h1     { background-color: blue; }
h1         { background-color: green; }
<!-- the background-color expected 
     to be pink for the following h1 -->
<div class="main" id="myid"> 
    <h1>This is paragraph one!</h1>
</div>
        
<!-- the background-color expected 
     to be brown for the following h1 -->
<div style="background-color:brown;" class="main" > 
    <h1>This is paragraph two!</h1>
</div>


Solution

  • Both of these have to do with whether the style is applied directly to the element or to the parent element.

    In both cases, your intuition is correct for the outer div.main element. However, there are rules that apply to the h1s that, while less specific, apply directly to the h1s so they take precedence over the more specific rules that apply to the divs.

    Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.

    https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#Directly_targeted_elements_vs._inherited_styles