CSS pseudo-classes are used to apply special styles to an element based on its state or position within the document tree. Here are some commonly used pseudo-classes:
:hover
: This pseudo-class is used to apply styles to an element when the mouse cursor is hovering over it.:active
: This pseudo-class is used to apply styles to an element when it is being activated, such as when a user clicks on a link.:focus
: This pseudo-class is used to apply styles to an element that currently has focus, such as a text input field.:first-child
: This pseudo-class is used to apply styles to the first child element of a parent element.:last-child
: This pseudo-class is used to apply styles to the last child element of a parent element.:nth-child()
: This pseudo-class is used to apply styles to elements that match a specific pattern based on their position in the parent element.:nth-of-type()
: This pseudo-class is similar to:nth-child()
, but it only applies to elements of a specific type.
Here are some examples of how these pseudo-classes can be used in CSS:
/* Styles for links when hovered over */
a:hover {
color: red;
}
/* Styles for text inputs when in focus */
input[type="text"]:focus {
border: 2px solid blue;
}
/* Styles for the first child element of a list */
ul li:first-child {
font-weight: bold;
}
/* Styles for even-numbered rows of a table */
tr:nth-child(even) {
background-color: lightgray;
}
/* Styles for odd-numbered paragraphs within a div */
div p:nth-of-type(odd) {
font-style: italic;
}
By using these pseudo-classes, you can create more dynamic and interactive styles that respond to user actions and the structure of your HTML document.