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 style elements based on user interaction, element state, or other criteria. Here are some common pseudo-classes in CSS along with examples:
1. :hover:
Applies styles when an element is being hovered over by the mouse cursor.Example:
HTML
<button class="btn">Hover over me</button>
CSS
.btn:hover {
background-color: blue;
color: white;
}
2. :active:
Applies styles when an element is being activated, such as when a button is clicked.Example:
HTML
<button class="btn">Click me</button>
CSS
.btn:active {
background-color: red;
color: white;
}
3. :focus:
Applies styles when an element has focus, such as when an input field is selected.Example:
HTML
<input type="text" class="input">
CSS
.input:focus {
border-color: green;
}
4. :first-child:
Selects the first child element of its parent.Example:
HTML
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
CSS
li:first-child {
color: blue;
}
5. :last-child:
Selects the last child element of its parent.Example:
HTML
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
CSS
li:last-child {
color: red;
}
6. :nth-child(n):
Selects elements based on their index, keyword (odd/even), or a functional cycle formula ($an+b$) within their parent element.HTML Structure:
HTML
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
Examples:
1. Odd / Even Selection:
CSS
2. Specific Index (nth-child(4)):
/* Target odd items (1st, 3rd, 5th...) */
li:nth-child(odd) {
background-color: lightgray;
}
/* Target even items (2nd, 4th, 6th...) */
li:nth-child(even) {
background-color: white;
}
CSS
3. Formula (an+b):
/* Targets exactly the 4th element */
li:nth-child(4) {
color: orange;
font-weight: bold;
}
CSS
/* Targets every 3rd element starting from the 1st (1, 4, 7...) */
li:nth-child(3n+1) {
color: purple;
}