Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does specificity work with inherited styles?

Tags:

css

HTML

<div class='container'>
  <p>foo</p>
</div>

CSS

.container {
  color: red;
}

p {
  color: blue
}

Code Pen


The applied color is blue. Why is this? I was thinking that since .container has more specificity than p, the color would end up being red.

What is happening here? Why is it blue?

My hypothesis is that the process is "Does p have any selectors? If so use it and don't look up for .container. If it didn't have any styles, it'd look up and use the style for .container."

like image 787
Adam Zerner Avatar asked Sep 18 '15 20:09

Adam Zerner


2 Answers

From the MDN page on Specifity

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

Hence p will override .container no matter what. The inherited style from .container is overwritten

like image 94
cjds Avatar answered Oct 24 '22 18:10

cjds


think of the css in this specific case as a target bulls eye. you start from the most specific pointer to your element in question.

in your example above, it is the p selector since the text is within the p tag wrapper. then going outward from that (the ring right outside the bulls eye, if you will) is the .container div. since the target p is closest to the text you want to color, it inherits that css (color text of blue).

in the example below:

.container {
  color: red;
}

p {
  color: blue
}
<div class='container'>
  i should be red text since im outside the p tag but inside the div container
  <p>foo</p>
</div>

you see that the text "i should be red...." doesnt necessarily have a "bulls eye" css, so it goes one ring outside and sees .container and is assigned the color red.

========

now to answer your question about specificity

specificity applies to a case like the example below:

.makeMeBlue {
  color: blue;
}

.makeMeBlue.actuallyMakeMeRed {
  color: red;
}
<div class="makeMeBlue">i am some random text</div>
<div class="makeMeBlue actuallyMakeMeRed">some more text here</div>

in the above example, you see that make .makeMeBlue has css to make the color of the text blue. however, the second .makeMeBlue div's text color is red. this is because we were more specific about targeting the second element. we used the selector .makeMeBlue.actuallyMakeMeRed utilizing both classes of the element to say "this is the element i want to target specifically and assign this css to".

so instead of the element being like "developers are blue, ok i'll be blue" it sees "hey, someone just said all developers who are named 'jason' are red, and my name is jason and i'm a developer - it is more specific to me, so i'll be red".

i hope that explained specificity a little more clearly.

like image 22
indubitablee Avatar answered Oct 24 '22 20:10

indubitablee