The :first-child pseudo-class selector in CSS is used to select the first child element of its parent element. This is useful when you want to apply styles specifically to the first child of a container, regardless of its type or class.
Syntax:
selector:first-child {
/* CSS properties */
}
Examples:
1. Basic Usage
Apply styles to the first child of a <ul>:
HTML:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
CSS:
ul li:first-child {
color: red; /* Styles the first <li> element inside the <ul> */
}
In this example, “Item 1” will be red because it is the first <li> child of the <ul>.
2. Applying Styles to the First Paragraph in a Container
HTML:
<div class="container">
<p>First paragraph</p>
<p>Second paragraph</p>
</div>
CSS:
.container p:first-child {
font-weight: bold; /* Makes the first <p> element bold */
}
Here, “First paragraph” will be bold because it is the first <p> child inside the .container div.
3. Combined with Other Selectors
You can combine :first-child with other selectors to target specific elements.
HTML:
<div class="cards">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</div>
CSS:
.cards .card:first-child {
border: 2px solid blue; /* Adds a blue border to the first .card element */
}
In this example, “Card 1” will have a blue border because it is the first .card inside the .cards container.
Important Notes:
- Element Type Matters: The
:first-childselector targets the very first child element of its parent, regardless of its type. If the first child is not of the type you intend to style, it won’t be selected. For example, if a<div>has a<p>followed by an<h1>, and you want to style the<h1>, using:first-childon the<h1>would not work if the<p>is the first child. - Combining with Other Pseudo-Classes: You can use
:first-childwith other pseudo-classes and selectors to refine your styling.
Example of Combining with :last-child:
ul li:first-child {
color: blue;
}
ul li:last-child {
color: green;
}
In this example, the first <li> will be blue, and the last <li> will be green.
Use Cases:
- Styling Lists: Highlighting or differentiating the first item in a list.
- Form Inputs: Applying different styles to the first input field in a form.
- Navigation Menus: Styling the first item in a navigation menu differently.
Browser Support:
The :first-child pseudo-class is well-supported in modern browsers, including Chrome, Firefox, Safari, Edge, and Internet Explorer 9 and above.
