Cascading & Specificity
Often, multiple style statements attempting to set the same properties refer to the same element. Which styles will win?
Cascading
We have already seen that styles can be set in three locations:
- In element attributes
- In a style element in the head element of a page
- In a style sheet linked to the page
Styles may also be defined in two other locations:
- The browser itself has default styles for all elements
- With some browsers, the user can make a setting in the browser to read a local stylesheet for all pages
The browser gathers all the styles for each element type and sorts them out according to the following criteria, listed here in descending order of priority:
- Styles from the user stylesheet that are flagged with ! important
- Styles in attributes, the style element, or linked stylesheets that are flagged with ! important
- Styles in attributes, the style element, or linked stylesheets (in other words, styles defined by the author)
- Styles from the user stylesheet
- Styles from the browser defaults
Tip: Much confusion can result from forgetting that the browser default styles are there, particularly since they vary among different browsers. For example, you might try to increase the indent of an unordered list by increasing the left margin. On some browsers it will work but on others it will produce too much indent because they use padding to create the indent. The solution is to use a reset or base style sheet.
Specificity
When styles for an element and property still conflict, the one with the more specific selector wins. If the selector for a style contains more IDs, more classes, and/or more element types than another selector, it is considered more specific. For example, consider the following two styles:
p { margin: 1em 4em 1em 4em; }
p.quote { margin-left: 2em; }
The p.quote style will determine the left margin because it has the class and is therefore more specific.
The more specific your style is defined the more likely it will be applied. To assign specificity to a style, you need to know the following rules:
- Count the number of element names in the selector.
- Count the number of pseudo-classes and other non-ID attributes in the selector, and multiply by 10.
- Count the number of ID attributes in the selector, and multiply by 100.
- Add up all three numbers, and that is that property's specificity.
The style with the higher specificity score wins.