Reputation: 757
Following is the html file I am working to understand difference between these two rules in CSS.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>specificity</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
aside,
article,
section,
header,
footer,
nav {
display: block;
}
body {
font-family: Georgia;
font-size: 120%;
}
/*add styles here*/
#mainContent p {
color: red;
}
p {
color: blue;
}
.green {
color: green;
}
/**/
</style>
</head>
<body>
<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>
</section>
</body>
</html>
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
strong
element above, we are seeing inheritance and not specificity.
But if I apply green
class to <p>
element, I am observing specificity since style green is ignored and style with id applied to paragraph.
My question is, since <p>
is a child of <section>
shouldn't inheritance be observed here according to above statement, just like it's observed with <strong>
element?
Upvotes: 0
Views: 120
Reputation: 82976
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.
Upvotes: 1