CSS Pseudo-classes

Pseudo-classes are a powerful feature in CSS that allow you to define special states of an element. They are used to style an element when it's in a certain state, such as when a user hovers over it, or when it has focus.

Mandatory reading
To understand all the cases, see the CSS Selector reference

What Are CSS Pseudo-classes?

A pseudo-class is used to define a special state of an element. For example, it can be used to style an element when it is hovered over, when it is checked, or when it is the first child of its parent.

Common CSS Pseudo-classes

Here are some of the most commonly used CSS pseudo-classes:

Examples of CSS Pseudo-classes

Here are practical examples demonstrating the use of different CSS pseudo-classes:

:hover Example


/* CSS */
a:hover {
    color: red;
}
/* HTML */
<a href="#">Hover over me!</a>

This example changes the text color to red when the user hovers over the link.

:focus Example


/* CSS */
input:focus {
    border: 2px solid blue;
}
/* HTML */
<input type="text" placeholder="Click or tab into me!">

This example highlights an input box with a blue border when it is focused.

:first-child and :last-child Example


/* CSS */
li:first-child {
    font-weight: bold;
}
li:last-child {
    color: green;
}
/* HTML */
<ul>
    <li>First item (bold)</li>
    <li>Second item</li>
    <li>Last item (green)</li>
</ul>

This example makes the first list item bold and the last list item green.

:nth-child() Example


/* CSS */
li:nth-child(2) {
    color: orange;
}
/* HTML */
<ul>
    <li>First item</li>
    <li>Second item (orange)</li>
    <li>Third item</li>
</ul>

This example colors the second list item orange.

:not() Example

/* CSS */
p:not(.exclude) {
    color: purple;
}
/* HTML */
<p class="exclude">Not targeted</p>
<p>Targeted (purple)</p>

This example applies purple color to all paragraphs except those with a class of 'exclude'.

Conclusion

Understanding and using CSS pseudo-classes effectively allows developers to create more dynamic, interactive, and responsive designs. By targeting specific states or conditions of elements, you can greatly enhance the user experience on your web pages.