Russell
Russell

Reputation: 97

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>

Upvotes: 3

Views: 129

Answers (3)

Temani Afif
Temani Afif

Reputation: 272909

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.

Upvotes: 1

user3774380
user3774380

Reputation: 1

The pink background is present, but it's being hidden by the red background of the H1 that's sat on top of it.

If you add some padding to the #myid styles the you will see a pink outline around the red of the H1

Upvotes: 0

Bryan
Bryan

Reputation: 1623

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

Upvotes: 5

Related Questions