CSS Pseudo-class Selector
The CSS pseudo-class selector is used to define a special state of an element, such as when a user hovers over it, when it is the first child of its parent, or when it is selected.
The syntax for a pseudo-class selector is:
</>
Copy
selector:pseudo-class {
property: value;
}
Where:
Parameter | Description |
---|---|
selector | The element or group of elements being styled. |
pseudo-class | The specific state of the element (e.g., :hover , :nth-child() ). |
property | A CSS property (e.g., color , background-color , etc.). |
value | The value assigned to the CSS property. |
Examples
Styling Links on Hover using :hover
Pseudo-class Selector
In this example, we change the color of links (<a>
) to red when the user hovers over them.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
a:hover {
color: red;
}
</style>
</head>
<body>
<a href="#">Hover over this link</a>
</body>
</html>
Styling First Child Elements using :first-child
Pseudo-class Selector
Here, we style the first <p>
element inside any <div>
, changing its font size to 18px.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div > p:first-child {
font-size: 18px;
}
</style>
</head>
<body>
<div>
<p>This paragraph is the first child.</p>
<p>This paragraph is not styled.</p>
</div>
</body>
</html>
Styling Odd-Numbered Table Rows using :nth-child
Pseudo-class Selector
In this example, we use the :nth-child(odd)
pseudo-class to apply a background color of #f0f0f0 to all odd-numbered rows in a table.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
tr:nth-child(odd) {
background-color: #f0f0f0;
}
</style>
</head>
<body>
<table border="1">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>
</body>
</html>
Styling Focused Input Fields using :focus
Pseudo-class Selector
In this example, we style input fields <input>
when they are focused, adding a border color of blue.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input:focus {
border: 2px solid blue;
}
</style>
</head>
<body>
<input type="text" placeholder="Focus me">
</body>
</html>