What are pseudo-classes in CSS?
CSS pseudo-classes are keywords added to selectors that specify a special state of the selected element(s), or select elements based on properties beyond their plain HTML element name, ID, or class. They allow you to apply styles based on interaction, position, or other dynamic criteria without altering the HTML structure.
What are CSS Pseudo-classes?
Pseudo-classes are used to define a special state of an element. For example, they can be used to style an element when a user mouses over it, style visited or unvisited links differently, or style an element that is the first child of its parent.
They are always prefixed with a single colon (:) in CSS selectors, distinguishing them from regular classes which use a dot (.).
Common Pseudo-class Categories and Examples
User Action Pseudo-classes
- <code>:hover</code>: Selects an element when the user's mouse pointer is over it.
- <code>:active</code>: Selects an element while it is being activated by the user (e.g., a button being clicked).
- <code>:focus</code>: Selects an element when it has received focus (e.g., an input field selected by tabbing or clicking).
- <code>:visited</code>: Selects links that the user has visited.
- <code>:link</code>: Selects unvisited links.
Structural Pseudo-classes
- <code>:first-child</code>: Selects the first element among a group of sibling elements.
- <code>:last-child</code>: Selects the last element among a group of sibling elements.
- <code>:nth-child(n)</code>: Selects elements based on their position among a group of siblings (e.g., <code>nth-child(odd)</code>, <code>nth-child(2n)</code>).
- <code>:nth-of-type(n)</code>: Selects elements of a specific type based on their position among siblings of the same type.
- <code>:only-child</code>: Selects an element that is the only child of its parent.
- <code>:empty</code>: Selects elements that have no children (including text nodes).
Other Useful Pseudo-classes
- <code>:not(selector)</code>: Selects elements that do not match the specified selector.
- <code>:root</code>: Selects the document's root element (typically <code><html></code>).
- <code>:target</code>: Selects the element whose ID matches the URL's fragment identifier (e.g., <code>#section1</code>).
Example Usage
a {
color: blue;
text-decoration: none;
}
a:hover {
color: red;
text-decoration: underline;
}
input:focus {
border: 2px solid green;
background-color: lightyellow;
}
li:nth-child(odd) {
background-color: #f0f0f0;
}
Why Use Pseudo-classes?
Pseudo-classes are incredibly powerful because they enable dynamic styling without requiring JavaScript or additional markup. They enhance user experience by providing visual feedback for interactions and simplify complex selections based on an element's state or position, leading to cleaner, more semantic, and maintainable CSS.