Inheritance and Specificity
This lesson is part of the Web Programming 1 Course.
This is a short but very important overview of two important concepts in CSS, which are **inheritance** and **specificity**.Inheritance
Some CSS properties are 'inherited', which means that if you apply them to an element, then the elements within it will inherit the property.
For example, consider this rule set:
body{
color: green;
}
This rule set targets the body element, and sets the color to green. Because the color property is one that is 'inherited', all of the elements within the body will inherit it, and display their content in green.
When designing a web site, it's very common to target the body element in order to set defaults for the page. So the above rule set basically set the default color for the page to green.
You can then override the default by targeting specific elements that are withing the body, for example:
p{
color: orange;
}
If we add this rule set to the page, all elements would default to a green color, but p elements would be orange.
Remember, not all properties get inherited (things could get really messy if they all did), but you don't really need to worry about which ones do and which ones don't for the purposes of this class.
Specificity
Look at these two rule sets:
.warning{
color: red;
}
h2{
color:blue;
}
One sets the color to red, while the other sets the color to blue. What happens if you have an h2 element with its class set to 'warning'? For example:
<h2 class="warning">What color will this be?</h2>
So, we have a conflict! To resolve this conflict, the rule set with the most specific selector will win. Class selectors are considered to be more specific than type selectors, so the h2 element above would be red
Here are the basic rules of specificity in CSS:
- Type selectors are the least specific
- Class selectors are more specific than type selectors
- ID selectors are the most specific
It makes sense that ID selectors are the most specific, because when you use one, you are specifically targeting a single element on the page.
Figuring out specificity can get complicated when you're working with complex mixed selectors like this one:
div.warning li.selected a{
color: blue;
}
But we don't need to worry about them for the purposes of this course.