CSS :first-child
The CSS :first-child pseudo-class applies styles to the first child element of its parent. It is useful for targeting and styling elements dynamically based on their position within their parent container.
The syntax for the :first-child
pseudo-class is:
</>
Copy
selector:first-child {
property: value;
}
Where:
Parameter | Description |
---|---|
selector | The element you want to apply the :first-child pseudo-class to. |
property | The CSS property to style the first child element. |
value | The value assigned to the CSS property. |
Examples
1. Changing Text Color of the First List Item
In this example, the text color of the first <li>
in an unordered list is set to red.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
li:first-child {
color: red;
}
</style>
</head>
<body>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
</body>
</html>
2. Highlighting the First Paragraph in a Section
Here, the first <p>
element inside a <div>
has a background color of yellow.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div p:first-child {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>First paragraph</p>
<p>Second paragraph</p>
</div>
</body>
</html>
3. Changing Font Size of the First Table Row
In this example, the font size of the first <tr>
in a table is increased.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
tr:first-child {
font-size: 1.5em;
}
</style>
</head>
<body>
<table border="1">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
</table>
</body>
</html>
4. Styling the First Heading in a Container
The first <h1>
inside a container is styled with blue text and a border.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
div h1:first-child {
color: blue;
border-bottom: 2px solid blue;
}
</style>
</head>
<body>
<div>
<h1>First Heading</h1>
<p>A paragraph follows.</p>
</div>
</body>
</html>
5. Targeting the First Child in a Nested List
In this example, the first child of a nested <ul>
is styled with bold text.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
ul ul:first-child {
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>Parent Item 1
<ul>
<li>Child Item 1</li>
<li>Child Item 2</li>
</ul>
</li>
<li>Parent Item 2</li>
</ul>
</body>
</html>