Sub topic 2
Counting with `:nth-child()` and An+B
Assume you know HTML structure, CSS selectors, combinators, and basic rule syntax. This chapter focuses on selecting elements by position, state, relationship, and specificity.
Counting with `:nth-child()` and An+B
:nth-child() selects an element by its position among all siblings. Its argument uses An+B, where n starts at zero. A is the repeating step, and B is the starting offset.
li:nth-child(even) {
background: #f5f5f5;
}
li:nth-child(3n + 1) {
font-weight: bold;
}
li:nth-child(-n + 3) {
color: #0645ad;
}These rules select even positions, positions 1, 4, 7, and so on, and the first three items. :first-child, :last-child, and :only-child handle common fixed positions.
Position among same-type siblings
:nth-of-type() counts only siblings with the same element type. This matters when different elements share a parent.
article p:nth-of-type(2) {
border-top: 1px solid #ccc;
}This selects the second p, even if a heading or another element appears before it. Related selectors include :first-of-type, :last-of-type, and :only-of-type.
Form state
Form pseudo-classes describe the current state of controls.
input:required:invalid:not(:placeholder-shown) {
border-color: #c00;
}
input:disabled {
opacity: 0.5;
}
input:checked + label {
font-weight: 600;
}:checked matches selected checkboxes and radio buttons. :disabled matches unavailable controls. :required marks required fields. :invalid matches values that fail built-in validation. :placeholder-shown matches an empty input displaying its placeholder. Combining :invalid with :not(:placeholder-shown) avoids showing an error before typing begins.
Grouping and filtering
:is() shortens repeated selector lists. :where() does the same but contributes zero specificity. :not() excludes matches. :has() selects an element based on its descendants.
:is(article, section) :is(h1, h2) {
line-height: 1.2;
}
.card:has(img) {
display: grid;
}Specificity
A normal pseudo-class adds class-level specificity. A pseudo-element adds element-level specificity. :is(), :not(), and :has() use the most specific argument inside them. :where() always has zero specificity, making it useful for defaults that are easy to override.
Exercise
Which selector matches list items 1, 3, 5, and 7?
Show answer
li:nth-child(2n + 1).