CSS pseudo-classes
CSS pseudo-classes are special selectors used to target and style elements based on their state or position within the document tree. They start with a single colon :
notation and allow you to apply styles to elements that are not based solely on their tag name, class, or ID.
Here are some commonly used CSS pseudo-classes:
:hover
: Selects an element when it is being hovered over by the mouse pointer.:active
: Selects an element when it is being activated or clicked (e.g., when a button is pressed).:focus
: Selects an element when it gains focus (e.g., when a form element like an input field is clicked or tabbed into).:visited
: Selects a link that has been visited by the user.:first-child
: Selects the first child element of its parent.:last-child
: Selects the last child element of its parent.:nth-child(n)
: Selects the nth child element of its parent, where “n” is a number, keyword, or formula.:nth-of-type(n)
: Selects the nth element of a particular type (e.g.,<p>
,<div>
) of its parent.:nth-last-child(n)
: Selects the nth child element of its parent, counting from the last child.:nth-last-of-type(n)
: Selects the nth element of a particular type of its parent, counting from the last element.:not(selector)
: Selects elements that do not match the specified selector.
Example:
/* Style links when hovered */
a:hover {
color: red;
text-decoration: underline;
}
/* Style input fields when focused */
input:focus {
border: 2px solid blue;
}
/* Style odd rows of a table */
tr:nth-child(odd) {
background-color: lightgray;
}
In the above examples, the first CSS rule applies styles to anchor (<a>
) elements when they are hovered over. The second rule styles input fields (<input>
) when they gain focus. The third rule styles odd rows of a table by using the :nth-child
pseudo-class.
CSS pseudo-classes offer a powerful way to apply styles dynamically based on user interactions or the structure of the document. They enhance the interactivity and visual appeal of a webpage and help create more engaging and user-friendly designs.