Sub topic 2
Pseudo-Classes, Pseudo-Elements, and Specificity
Assume you know basic HTML, attributes, and how to link a stylesheet. You should also know common CSS properties such as color and margin.
Pseudo-classes
A pseudo-class selects an element based on its state or position. It starts with a colon.
a:hover {
color: darkblue;
}
input:focus {
outline: 2px solid orange;
}
li:first-child {
font-weight: bold;
}:hover matches while the pointer is over an element. :focus matches the element receiving keyboard or other input focus. :first-child matches an element that is the first child of its parent. Other useful pseudo-classes include :checked, :disabled, :last-child, and :not().
Pseudo-elements
A pseudo-element styles a particular part of an element or creates generated content. It starts with two colons.
p::first-line {
font-weight: bold;
}
.external-link::after {
content: " ↗";
}::first-line selects the first line of text. ::before and ::after can generate content when their content property is set.
Selector Lists and Grouping
A comma creates a selector list. Each selector is matched independently, which avoids repeating the same declaration.
h1, h2, h3 {
font-family: sans-serif;
}The selectors in a list do not share specificity. For example, #title, p contains one selector with ID specificity and one with type specificity.
Calculating Specificity
Specificity predicts which matching declaration wins. Write it as (IDs, classes/attributes/pseudo-classes, types/pseudo-elements).
article p.note { color: green; } /* (0,1,2) */
#news p { color: blue; } /* (1,0,1) */The second rule wins because one ID outweighs any number of classes or types in the lower columns. Combinators such as > and spaces add no specificity. :is() uses its most specific argument, while :where() always contributes zero.
Inheritance and Why It Loses to Direct Rules
Some properties, such as color and font-family, inherit from a parent. An inherited value is used only when the element has no winning declaration of its own.
body { color: #333; }
.note { color: darkred; }A paragraph inside .note receives darkred from its direct rule. A paragraph outside .note inherits #333 from body.
Exercise
What is the specificity of nav > a.active:hover?
Show answer
(0,2,2): one class, one pseudo-class, one type, and one pseudo-class target type (a).