Sub topic 1
Selectors You Already Use, and Where Pseudo Selectors Fit
Prerequisites
You should know basic HTML, CSS rule syntax, type, class, ID, and attribute selectors, plus descendant and child combinators. This chapter assumes you already understand that a selector chooses elements and a declaration changes their style.
A pseudo-class selects an element in a particular state, position, or relationship. A pseudo-element selects a part of an element or generated content that has no HTML tag.
One Colon or Two
Pseudo-classes use one colon:
button:hover {
background: #2457a6;
}
li:first-child {
font-weight: bold;
}Pseudo-elements use two colons:
.card::before {
content: "";
display: block;
height: 4px;
background: #2457a6;
}The button and li selectors identify ordinary elements. The pseudo selector adds a condition or identifies a special part.
Reacting to the User
Use :hover when a pointer is over an element, :active while it is being activated, and :focus when it has keyboard or programmatic focus. Prefer :focus-visible for a focus indicator that browsers show when it is useful, especially during keyboard navigation. :focus-within matches a container when the container or one of its descendants has focus.
button:hover {
background: #2457a6;
}
button:active {
transform: translateY(1px);
}
button:focus-visible {
outline: 3px solid #f2b134;
outline-offset: 2px;
}
.form-group:focus-within {
background: #f0f6ff;
}Do not remove focus indicators without providing another clear indicator.
Link States and LVHA Order
For links, remember LVHA: :link, :visited, :hover, and :active. When selectors have equal specificity, later matching rules win.
a:link {
color: #0645ad;
}
a:visited {
color: #6b3fa0;
}
a:hover {
text-decoration: underline;
}
a:active {
color: #c00;
}Selecting by Position
Structural pseudo-classes use an element’s relationship to its parent:
:first-childmatches the first child.:last-childmatches the final child.:only-childmatches an element with no siblings.:emptymatches an element with no child nodes, including no text.:rootmatches the document’s root element, normallyhtml.
article p:first-child {
margin-top: 0;
}
.menu li:last-child {
border-bottom: 0;
}
.panel:empty {
display: none;
}
:root {
color-scheme: light;
}Exercise
Which selector matches a section when it contains no child nodes?
Show answer
section:empty.