3

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>

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

as a side note, background is not inherited, it's transparent by default ... so the inheritance doesn't apply here
Thank you. You are right, these styles are not applied directly on h1.
1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.