CSS Pseudo-classes
A pseudo-class is a keyword added to a selector that targets an element in a particular state, such as being hovered, focused, or checked.
Pseudo-classes let you style elements based on information that is not in the document tree, like user interaction or form state. You write them with a single colon after a selector, and they are extremely common in interactive interfaces.
Common interactive pseudo-classes
Styling link and button states
Hover and focus
<!DOCTYPE html>
<html>
<head>
<style>
.btn {
background: #00643c;
color: #fff;
}
.btn:hover {
background: #00502f;
}
.btn:focus {
outline: 2px solid #00643c;
}
</style>
</head>
<body>
<button class="btn">Submit</button>
</body>
</html>Note: Always keep a visible :focus style. Removing outlines without a replacement makes a page hard to use for people navigating with a keyboard.
Form state pseudo-classes
Reacting to a checkbox
<!DOCTYPE html>
<html>
<head>
<style>
input:checked + label {
font-weight: bold;
}
input:disabled {
opacity: 0.5;
}
</style>
</head>
<body>
<input type="checkbox" id="subscribe">
<label for="subscribe">Subscribe to updates</label>
<br>
<input type="text" disabled value="Disabled field">
</body>
</html>Pseudo-classes can also be combined with combinators, as in the example above where a checked input styles the label right after it. Position-based pseudo-classes such as :first-child are covered in Structural Pseudo-classes.
Exercise: CSS Pseudo-classes
What is the general purpose of a CSS pseudo-class?