Kiran Kiran - 2 years ago 62
HTML Question

Confusion between inheritance and specificity in CSS

Following is the html file I am working to understand difference between these two rules in CSS.


<meta charset="UTF-8">
<!--[if lt IE 9]>
<script src=""></script>
nav {
display: block;
body {
font-family: Georgia;
font-size: 120%;
/*add styles here*/
#mainContent p {
color: red;
p {
color: blue;
.green {
color: green;

<section id="mainContent">
<p>I am a paragraph nested inside a section. I also have a <strong class="green">strong tag</strong> nested inside of me.</p>


And following is the statement I didn't understand quite clearly:

Specificity works just fine until inheritance is involved. If a child
element has a style that differs or conflicts with the parent styles,
the child styles always win. So for
element above, we are seeing inheritance and not specificity.

But if I apply
class to
element, I am observing specificity since style green is ignored and style with id applied to paragraph.

My question is, since
is a child of
shouldn't inheritance be observed here according to above statement, just like it's observed with

Answer Source

Every CSS rule only applies to the subject of its selector.

For p { ... } the subject is all p elements

For #mainContent p { ... } the subject is all p elements which are inside the element with id mainContent.

if a p element is inside the element with id mainContent, the #mainContent p { ... } rule wins because it is a more specific rule.

The strong element is not the subject of either rule, so neither applies directly.

In the example, the strong element is the subject of the .green { ... } rule. So that is the rule that applies to that element.

So where does inheritance come in?

Inheritance of a property to an element can happen in one of two ways.

First, there can be an explicit rule whose subject is the element and the property setting is inherit. So strong { color:inherit; } will, if it is the highest priority rule with the color property in the cascade for a strong element, force the color of that element to be taken from that of its parent.

Alternatively, if there is no rule anywhere in the cascade for which a given strong element has a particular property defined, that element will take a default value. Some properties are defined as "inherited" and others are not. The color property is defined as inherited.

So, in this alternative case, only when that there is no rule whose subject is a given element and has a color property, does the color of that given element get inherited from the color of the containing element.

In your example. there are multiple rules for which the p element is the subject and the color element is defined, so no inheritance is effective on that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download