- Home
- /
- Tutorials
- /
- CSS Tutorial
- /
- CSS Pseudo Classes
CSS Advanced Selectors
CSS Pseudo Classes
CSS Pseudo Classes are used to define a special state of an HTML element.
They allow you to style elements based on:
- User interaction
- Element position
- Form state
- Dynamic conditions
Pseudo classes start with a colon (:) and are widely used to create interactive and responsive user interfaces.
Common examples include:
- :hover
- :focus
- :first-child
- :last-child
- :nth-child()
Syntax
CSS Pseudo Classes Syntax
css
selector:pseudo-class {
property: value;
}CSS Pseudo Classes Example
css
a:hover {
color: red;
}Changes the link color when the mouse pointer hovers over it.
Attributes
| Pseudo Class | Description | Example |
|---|---|---|
| :hover | Styles an element when hovered | a:hover |
| :focus | Styles an element when focused | input:focus |
| :first-child | Selects the first child element | p:first-child |
| :last-child | Selects the last child element | p:last-child |
| :nth-child() | Selects a specific child | li:nth-child(2) |
Example
CSS Pseudo Classes Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo Classes Example</title>
<style>
a:hover {
color: red;
}
input:focus {
border: 2px solid blue;
outline: none;
}
li:first-child {
color: green;
font-weight: bold;
}
li:last-child {
color: orange;
}
li:nth-child(2) {
color: purple;
}
</style>
</head>
<body>
<a href="#">Hover over this link</a>
<br><br>
<input type="text" placeholder="Click here">
<br><br>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>React</li>
</ul>
</body>
</html>Output
Browser Output
css
The link will turn red when hovered
The input field will show a blue border when focused
The first list item (HTML) will appear in green
The second list item (CSS) will appear in purple
The last list item (React) will appear in orangeBrowser Support
Chrome | Edge | Firefox | Safari | Opera | IE |
|---|---|---|---|---|---|
| Yes | Yes | Yes | Yes | Yes | Yes |
Notes
- Pseudo classes are dynamic and respond to user actions.
:hoveris commonly used for buttons, links, and menus.:focusimproves accessibility and form usability.:nth-child()supports formulas.
Example:
nth-child Formula Example
css
li:nth-child(odd) {
background-color: #f5f5f5;
}Styles all odd-numbered list items.
Popular Pseudo Classes
| Pseudo Class | Use Case |
|---|---|
| :hover | Mouse interaction |
| :focus | Active form field |
| :active | Clicked element |
| :first-child | First item in a group |
| :last-child | Last item in a group |
| :nth-child() | Specific item selection |
Conclusion
CSS Pseudo Classes allow you to style elements based on their state, position, or user interaction. They are essential for creating interactive, accessible, and visually engaging websites without using JavaScript.
