Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 802
Russell Avatar asked Dec 02 '25 22:12

Russell


2 Answers

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

like image 110
Bryan Avatar answered Dec 04 '25 14:12

Bryan


You are not applying the background to h1 element but to its parent element. Considering this, there is no specificity here because we only consider the rules applied to h1 and if no rules we consider inheritance (the styles applied to parent element that get inherited by childs). Also background is not a value that get inherited by default so inheritance will not apply here even if you don't specify a background to h1.

So in this case the red will always win because it's the rule with highest specificity applied directly to h1.

like image 45
Temani Afif Avatar answered Dec 04 '25 14:12

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!