About Lesson
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. :nth-child(n):
Selects elements based on their position within their parent.
HTML
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
CSS
li:nth-child(odd) {
background-color: lightgray;
}