Introduction to CSS Selectors
CSS works on the principles of Cascading, Inheritance, and Specificity.
- Cascading means that the order of the rules matter; if two rules have equal specificity, the last one will apply.
- Specificity is how the browser selects a rule if there are more than one that could apply to an element. For example, class selectors are more specific than element selectors.
- Some CSS property values set on a parent are inherited (like font family), but some aren't (like width).
CSS Selectors
Selector Type |
Description |
header |
Selects an html element |
.caption |
Selects an html class |
#title |
Selects an html id tag |
Specificity increases from top to bottom |
Chaining Selectors
Selectors can be chained in a number of ways:
- Nested elements can be selected by separating selectors with a space
- Unrelated elements can be selected by separating the selector names with commas
Specificity
In the table above, specificity increases from top to bottom. Element selectors are the least specific, then class, then ID.