#navigation {
background: yellow;
}
.blueBackground {
background: blue;
}
.redBackground {
background: red;
}
This setup creates a situation where the browser needs to establish which value for the ‘background’ rule should be honoured as the most important one. Enter the cascading nature of CSS.
In these situations where a conflict is apparent on an element, the browser will look at the circumstances of the styles, and decide which has more ‘priority’. Let’s take a look at how priority is deemed with CSS.
First the browser will look at how the style is applied to the element and apply a weighting system based on this. From most to least important, the cascading system looks something like this:
- Inline styles. Inline styles are deemed the most important element and will almost always have top priority in the event of a conflict. Because the style is applied directly to the element, the browser assumes that this is the style that you intend to have operating on the element, and as such this is the style from which the conflicting property will be selected.
- External/internal style sheets. If no inline styles are applied to the element, then the browser will choose the property from the external/internal file (in this case, the internal file means the code in the style tag in the head of the document). In this case the browser will also apply a system of weighting based on the last occurring property in the document. For example, if I had two conflicting class styles defined on an element, the browser would go through the css file and look for the last occurrence of that conflicting property and use that. Therefore, if the style is defined lower down in the document, it is deemed more important, and therefore honoured. Likewise, if the style tag is used in the head section after the link tag referencing the stylesheet, then that internal sheet will be deemed more important, and within that internal sheet, the same principles apply, of lower down means more important.
- Browser default. Remember when we first generated our HTML in Chapter 2 and the browser outputted some default styling, for example our <h1> tags were bold and given a larger font size than our <p> tags? Well, this was the work of what we call a browser default. To help us out a bit, browsers come shipped with standard styles for commonly used HTML elements, such as text elements, where the browser will default to a helpful style in line with the nature of the tag. If no other style is operating on an element, this is what the browser will use to render your content.