Pseudo-classes in CSS
In CSS, pseudo-classes are keywords that can be added to selectors to target elements in a specific state, such as when they are being hovered over, clicked, or checked. Let’s explore some common pseudo-classes: :hover
, :active
, :checked
, and :nth-of-type
.
1. :hover
The :hover
pseudo-class is applied when the user hovers over an element with a pointing device (like a mouse). It is commonly used for interactive elements like links, buttons, or images.
Example: In this example, we have used the Hover() pseudo-class on the button which will hover and change to black
button:hover {
background-color: black;
color: wheat;
}
2. :active
The :active
pseudo-class applies when an element is being clicked or pressed by the user. It represents the state of an element while it is being activated (e.g., a button or link while it is being pressed down).
Example: In this example, whenever we click on paragraph P it will get active and green
button:active{
background-color: pink;
color: black;
}
p:active{
font-weight: 900;
color: green;
}
3. :checked
The :checked
pseudo-class is used to style checkboxes, radio buttons, and <option>
elements when they are in the checked (or selected) state. This is useful when styling forms or toggles.
Example: In this example, we have used checked pseudo class on radio button
input[type="radio"]:checked + label{
color: red;
font-weight: bolder;
}
4. :nth-of-type()
The :nth-of-type()
pseudo-class selects elements that match a certain pattern based on their position among siblings of the same type (tag). It allows for complex styling of elements in a specific sequence.
Example: In this example, we have used nth-of-type(2) on div and here 2 means the second div will be highlighted
nth-of-type(2n) → means every second div will be highlighted
nth-of-type(n) → means every div will be highlighted
div:nth-of-type(n){
background-color: antiquewhite;
}
Subscribe to my newsletter
Read articles from dheeraj koranga directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by