CSS Pseudo-classes
CSS pseudo-classes are keywords added to selectors that specify a special state of the selected elements. They allow you to apply styles to elements based on their state or position in the document without needing to add additional classes to your HTML.
Common CSS Pseudo-classes
1. :hover
The `:hover` pseudo-class applies styles to an element when the user hovers over it with the mouse. This is commonly used for links and buttons to provide visual feedback.
/* Hover Pseudo-class */
a:hover {
color: red;
}
Hover over me!
2. :focus
The `:focus` pseudo-class applies styles to an element when it has focus, such as when a user clicks on an input field or navigates to it using the keyboard.
/* Focus Pseudo-class */
input:focus {
border-color: blue;
outline: none;
}
3. :nth-child()
The `:nth-child()` pseudo-class matches elements based on their position in a parent element. It can take a number or a formula to select elements according to their order.
/* nth-child Pseudo-class */
li:nth-child(odd) {
background-color: #f0f0f0;
}
li:nth-child(even) {
background-color: #e0e0e0;
}
- Item 1
- Item 2
- Item 3
- Item 4
4. :first-child and :last-child
The `:first-child` and `:last-child` pseudo-classes match the first and last child elements within their parent, respectively.
/* first-child and last-child Pseudo-classes */
ul li:first-child {
font-weight: bold;
}
ul li:last-child {
font-style: italic;
}
- First item
- Second item
- Third item
5. :nth-of-type()
The `:nth-of-type()` pseudo-class matches elements based on their position among sibling elements of the same type.
/* nth-of-type Pseudo-class */
p:nth-of-type(2) {
color: green;
}
First paragraph
Second paragraph (This will be green)
Third paragraph