Selectors (classes and IDs) allow designers to “pick out” elements that might need to be displayed differently. When and how should you assign these selectors?
Generally, classes and IDs should be applied as sparingly as possible. Use selectors for HTML elements that are different in function. For example, this paragraph is not functionally different to the paragraph before or after, so this paragraph does not need a selector.
Classes and IDs apply their rules slightly differently, so choosing between them requires understanding how they work.
Cascading Rules: Precedence and Specificity
The name “Cascading Stylesheets” comes from how the web browser “cascades” different rules into a merged set of styles to apply to the HTML. Basically, less specific rules are always overwritten by more specific rules.
In this example from the previous section, all page links will be coloured red except links with the “selected” class assigned to them, which will be coloured black (because the .selected a rule is more specific):
a {
color: red;
}
.selected a {
color: black;
}
The Order of Precedence
How does the browser decide what is less or more specific? When calculating which styles are applied to an HTML element, the browser will prioritise in this basic order:
- #id
- .class
- html (HTML tag selector)
If two rules have equal precedence, the last rule in the stylesheet will be applied.
The Order of Precedence (with Multiple Selectors)
Calculating the order of precedence can be quite complicated when there are multiple selectors. An easy way to remember how the cascade works is to think of the selectors as a tree, with “higher” rules taking precedence over “lower” rules:
- #id
- #id html
- #id html html
- …
- #id .class
- #id #id
- #id html
- .class
- .class html
- .class .class
- .class #id *
- html
- html html
- html .class
- html #id *
* It is better to write selectors so they match the order of precedence (highest to lowest precedence, from left to right) to avoid confusion.
How to assign an ID
IDs take the highest precedence when CSS rules are applied.
- IDs must be singular and unique – an element can only have one ID, and the same ID cannot be used for multiple elements
- IDs should be used sparingly and carefully, because their rules might accidentally override other rules
- IDs are best used for structural, “containing” elements – eg. layout
divs (header, footer and other “container divs”)
How to assign a class
Classes take the second highest precedence when CSS rules are applied.
- Classes can be used multiple times – the same class name can be reused for multiple elements
- Multiple classes can be assigned to the same element – this is done by adding a space between each class name, eg.
class="menuitem first selected" - Classes are best used for “minor adjustments” to special elements – eg. the selected item in a list
- Classes are also used for special components that may appear multiple times on a page – eg. a button element
