What are CSS pseudo-classes?
John Mwaniki / Updated on 07 Jul 2024As a web developer, you may have come across the term "pseudo-classes" or stuff like :focus
, :hover
, :last-child
in CSS. If you're wondering what they are, this article will explain everything you need to know about CSS pseudo-classes.
What are CSS pseudo-classes?
CSS pseudo-classes are a way of selecting and styling elements based on their state or position in the document. They are indicated by a colon (:) followed by the pseudo-class name.
Syntax
selector:pseudo-class {
property: value;
}
The selector can be an HTML element, its class, or its Id attribute.
Below are some of the most commonly used pseudo-classes in CSS:
:hover
Used to select and style an element when the user hovers over it with their mouse cursor. For example, you can change the background color of a button when the user hovers over it:
button:hover {
background-color: yellow;
}
:active
Used to select and style an element when it is being clicked or activated. For example, you can change the color of a link when the user clicks on it:
a:active {
color: #F44336;
}
Click me!
:focus
Used to select and style an element when it receives focus. For example, you can change the border color of a text input field when the user clicks on it:
input:focus {
border-color: green;
}
:first-child
Used to select and style the first child element of a parent element. For example, you can change the color of the first paragraph in a div element:
div p:first-child {
color: purple;
}
This is the first sentence
This is the second sentence
This is the third sentence
:nth-child
Used to select and style an element based on its position among its siblings. For example, you can change the background color of the second paragraph in a div element:
div p:nth-child(2) {
background-color: orange;
}
This is the first sentence
This is the second sentence
This is the third sentence
Or you can change the background color of every even row in a table:
tr:nth-child(even) {
background-color: lightgray;
}
Name | Age |
---|---|
Gandalf | 83 yrs |
Frodo | 42 yrs |
Aragorn | 64 yrs |
Saruman | 93 yrs |
The above are just a few examples of CSS pseudo-classes. There are many more that you can use to create dynamic and interactive web pages.
Now you know what pseudo-classes in CSS are and what they are used for.