A pseudo-class is used to define a special state of an element.
For example, it can be used to:
- Style an element when a user mouses over it
- Style visited and unvisited links differently
- Style an element when it gets focus
The syntax of pseudo-classes:
selector:pseudo-class {
property: value;
}
: first-child
The :first-child selector is used to select the specified selector, only if it is the first child of its parent.
HTML and CSS code
<!DOCTYPE html>
<html>
<head>
<style>
p:first-child {
background-color: red ;
color:white;
font-weight:800;
padding:10px;
}
</style>
</head>
<body>
<p>This paragraph is the first child of its parent (body).</p>
<p>This paragraph is not the first child of its parent (body).</p>
<div>
<p>This paragraph is the first child of its parent (div).</p>
<p>This paragraph is not the first child of its parent (div).</p>
</div>
</body>
</html>