Specificity
The order isn’t everything, though. Before the cascade looks at the order, it compares how specific the selectors are, that is, how precisely they target the element. The more specific selector wins, even if it is written earlier. The order decides only between equally specific selectors.
From the most specific to the least specific:
- an id, such as
#title, - a class, an attribute selector or a pseudo-class, such as
.group,[target="_blank"]or:hover, - a type, such as
h1.
The universal selector * doesn’t count at all, so any other selector wins over it.
.group {
background-color: linen;
}
div {
background-color: white;
}Here, the groups stay beige even though the rule for div comes later: a class is more specific than a type.
When a selector consists of several parts, they add up: one id wins over any number of classes, and one class wins over any number of types. That’s why .group:hover (a class and a pseudo-class) wins over .group (just a class), and the background of a group changes on hover. And footer p (two types) would win over p (one type).
Styles in the style attribute win over all selectors. That’s one more reason to avoid them: they are hard to override.
Instructions
- 1
At the very beginning of
style.css, create a rule for the idtitlethat setscolor: darkred. Even though the rule forh1sets the color later in the file, the main heading will be dark red, because an id is more specific than a type.