CSS First Child Selector
CSS :first-child selector is used to select the elements that are the first child of the parent element.
Syntax:
:first-child {
/* CSS property */
}
Example 1: This example shows the use of the CSS first child selector.
<!DOCTYPE html>
<html>
<head>
<title>first child selector</title>
<style>
h1 {
color: green;
}
p:first-child {
background-color: green;
color: white;
font-weight: bold;
}
body {
text-align: center;
}
</style>
</head>
<body>
<p>GeeksforGeeks</p>
<h1>GeeksforGeeks</h1>
<h2>:first-child Selector</h2>
<p>GeeksforGeeks</p>
<div>
<p>GFG</p>
<p>Geeks</p>
</div>
</body>
</html>
Output:
Example 2: This example shows the use of the CSS first child selector.
<!DOCTYPE html>
<html>
<head>
<title>first child selector</title>
<style>
h1 {
color: green;
}
h1,
h2 {
text-align: center;
}
li:first-child {
background: green;
}
body {
width: 70%;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h2>:first-child Selector</h2>
<ul>
<li>Data Structure</li>
<li>Computer Network</li>
<li>Operating System</li>
</ul>
<ol>
<li>Java</li>
<li>Ruby</li>
<li>Pascal</li>
</ol>
</body>
</html>
Output:
Supported Browsers:
- Apple Safari 3.1 and above
- Google Chrome 4.0 and above
- Edge 12.0 and above
- Firefox 3.0 and above
- Opera 9.5 and above
CSS :first-child Selector – FAQs
What does the :first-child selector do in CSS?
The :first-child selector targets an element that is the first child of its parent element.
How do I style the first paragraph in a container?
Use the :first-child selector, like div p:first-child { font-weight: bold; }, to style the first paragraph within a div container.
Does :first-child work with all element types?
Yes, the :first-child selector can target any element type that is the first child of its parent, regardless of its tag.
Can :first-child be combined with other pseudo-classes?
Yes, :first-child can be combined with other pseudo-classes, such as :hover or :active, to apply more specific styling.
Is the :first-child selector supported by all browsers?
Yes, the :first-child selector is supported by all modern browsers, including older versions.