CSS Pseudo-class
What is a Pseudo-Class in CSS ?
In CSS, pseudo-classes allow you to apply styles to elements based on their state, position, or interaction without adding extra classes or IDs. Pseudo-classes begin with a colon (:) and are attached to selectors.
Syntax:
In CSS, pseudo-classes allow you to apply styles to elements based on their state, position, or interaction without adding extra classes or IDs. Pseudo-classes begin with a colon (:) and are attached to selectors.
Syntax:
selector:pseudo-class { property: value;}
Commonly Used Pseudo-Classes
1. :hover – Style on Mouse Hover
The :hover pseudo-class applies a style when a user places their mouse pointer over an element. It's commonly used for links, buttons, or interactive elements.
Example:
pseudo-class | Description |
---|---|
:active | It is used to add style to an active element. |
:hover | It adds special effects to an element when the user moves the mouse pointer over the element. |
:link | It adds style to the unvisited link. |
:visited | It adds style to a visited link. |
:lang | It is used to define a language to use in a specified element. |
:focus | It selects the element which is focused by the user currently. |
:first-child | It adds special effects to an element, which is the first child or another element. |
1. :hover – Style on Mouse Hover
The :hover pseudo-class applies a style when a user places their mouse pointer over an element. It's commonly used for links, buttons, or interactive elements.
Example:
<!DOCTYPE html><html>
<head> <style> body { text-align: center; }
h1:hover { color: red; }
h2:hover { color: blue; } </style></head>
<body> <h1>Hello World</h1> <h2>This is an example of :hover pseudo-class</h2></body>
</html>
Output:
.webp)
2. :active – Style on Click
The :active pseudo-class is triggered while an element is being clicked (like a button or link). It helps provide feedback during interaction.
Example:
The :active pseudo-class is triggered while an element is being clicked (like a button or link). It helps provide feedback during interaction.
Example:
<!DOCTYPE html><html>
<head> <style> body { text-align: center; }
a:active { color: yellow; }
h1, h2, h3 { color: red; } </style></head>
<body> <h1>Hello World</h1> <h2>The :active pseudo-class</h2> <h3>Click the following link to see the effect</h3> <a href="#">Click the link</a></body>
</html>
Output:
.webp)
Key Point
- Pseudo-classes enhance interactivity and style dynamically.
- No need to add extra HTML attributes or JavaScript.
- Common examples: :hover, :active, :focus, :visited, :first-child, :nth-child().