A pseudo-class in CSS is a keyword added to a selector that specifies a special state of the selected element(s) . Pseudo-classes are used to add styles to selectors, but only when those selectors meet certain conditions. They are keywords that start with a colon, such as :hover, :visited, :focus, and :active. Pseudo-classes let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator, the status of its content, or the position of the mouse.
Pseudo-classes can be used to:
- Style an element when a user mouses over it
- Style visited and unvisited links differently
- Style an element when it gets focus
Pseudo-classes can be combined with HTML classes to create more specific selectors. They can also be used to select elements that are in a specific state, such as the first element of their type or being hovered over by the mouse pointer.
Examples of commonly used pseudo-classes include:
- :hover
- :visited
- :focus
- :active
- :first-child
- :last-child
- :nth-child
- :not
Pseudo-classes can be used to create more flexible and maintainable code by reducing the need for excess classes in markup.