Order, Inheritance and Specificity in CSS
Some quick notes on an easily misunderstood area of CSS.
One thing to remember with CSS is the order statements appear in the stylesheet is important along with inheritance and specificity. So if you have the following:
div {
background-color: red;
}
... snip ...
div {
background-color: green;
}
The green background will be applied. This is also true across multiple stylesheets. Rules from stylesheets linked later in the HTML will take precedence over stylesheets appearing earlier in the HTML.
Inheritance allows some styles to be inherited. Not all styles are, but generally the ones you would want to be inherited are. So borders aren't inherited but font and colour information generally is, so if you do:
body {
color: blue;
font: 0.9em bold verdana, sans-serif;
}
p {
border: 1px solid gray;
}
span {
color: green;
}
In this case all text on the page would be a medium sized Verdana in blue, except spans which would be a medium sized Verdana in green. All paragraphs would have a grey border, but span tags within paragraphs wouldn't have the border.
Specificity is a little more complicated but assigns a sort of weighting to how rules are applied. Tags have the least 'weight', then classes / attributes, then ids then inline styles (styles set with the style attribute in the HTML). So using the previous example as a base, if we added the following rules:
.orange {
border: 1px solid orange;
}
#border {
border: 1px solid red;
}
Any HTML tag, including p's, with a class of orange would display an orange border, despite the previous p rule in the stylesheet. A p with an id of border and a class of orange would display a red border because the id is more specific than the class and the tag selector.
The way you write your selectors is also important for specificity. The more specific your selector is the higher the specificity. That's a very confusing sentence but what it means is if you had div p as your selector it would have more weight than p on its own. Building on our body / p /span example from before, we can add the following rules:
p span {
color: red;
}
.bordered {
border: 1px solid gray;
}
p.bordered {
border: 1px solid blue;
}
In this example all spans would be green, except those within p's, which would be blue. All tags with a class of bordered would have a grey border except for p's with a class of bordered. They'd have a blue border.
Specificity, order and inheritance are important areas to understand in CSS, but specificity in particular can be confusing. If anyone wants any more information and Google doesn't help, contact me directly or post something in the comments.