Learn how to style elements based on their state or position using CSS pseudo-classes like :hover, :focus, :nth-child(), and :not().
A pseudo-class is a keyword added to a selector that targets elements based on a specific state or position in the document tree. They are prefixed with a single colon :.
Unlike regular selectors that match elements by their tag name, class, or ID, pseudo-classes let you style elements based on dynamic conditions — whether the user is hovering, whether a field has focus, or where an element sits among its siblings.
:hover — When the user's pointer is over the element.:focus — When the element has keyboard focus (e.g., a clicked input or a tabbed-to button).:active — During the moment the element is being activated (e.g., while a button is pressed down).:visited — A link the user has already visited.:disabled / :enabled — Form elements that are disabled or enabled.:checked — Checkboxes or radio buttons that are selected.Structural pseudo-classes target elements based on their position among siblings:
:first-child — The element that is the first child of its parent.:last-child — The element that is the last child of its parent.:nth-child(n) — Targets elements by their position. The argument can be a number, a keyword, or a formula:
:nth-child(3) — the 3rd child:nth-child(odd) — 1st, 3rd, 5th, ... children:nth-child(even) — 2nd, 4th, 6th, ... children:nth-child(3n) — every 3rd child (3, 6, 9, ...):nth-child(2n+1) — same as odd:only-child — An element that has no siblings.:not(selector) — Matches elements that do not match the given selector. For example, p:not(.special) targets all paragraphs that lack the class special.<style>
ul {
list-style: none;
padding: 0;
}
li {
padding: 8px 12px;
border-bottom: 1px solid #ddd;
}
/* First item gets a top border */
li:first-child {
border-top: 1px solid #ddd;
font-weight: bold;
}
/* Alternate row coloring */
li:nth-child(odd) {
background-color: #f9f9f9;
}
/* Last item has special color */
li:last-child {
color: crimson;
}
/* Hover effect */
li:hover {
background-color: #e0e0e0;
}
</style>
<ul>
<li>First item (bold + top border)</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Last item (crimson)</li>
</ul>What does the selector `li:nth-child(even)` target?