Targeting the First Child
Part of the CSS Mastery section of Coddy's HTML journey — lesson 13 of 43.
The :first-child pseudo-class targets the first element among a group of sibling elements.
For example:
<section>
<p>This paragraph will be blue and bold.</p>
<p>This paragraph will have default styling.</p>
</section>Any paragraph that is the first child element within its parent will be colored blue and have bold text.
p:first-child {
color: blue;
font-weight: bold;
}You can combine and apply descendant, child, and other selectors to target elements more specifically. Here is another example:
div:first-child h1 {
color: red;
}This selects the first div element among its siblings, and then changes the text color of the <h1> tag inside it to red.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a CSS rule that targets the first list item (<li>) in any unordered list (<ul>) and styles it with:
- Blue text color
- A background color of light yellow
- A left padding of 10 pixels
Cheat sheet
The :first-child pseudo-class targets the first element among a group of sibling elements.
p:first-child {
color: blue;
font-weight: bold;
}You can combine :first-child with other selectors for more specific targeting:
div:first-child h1 {
color: red;
}This selects the first div element among its siblings, then targets the h1 tag inside it.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Targeting the First Child</title>
<style>
/* Write your CSS rule here */
</style>
</head>
<body>
<h2>Grocery List</h2>
<ul>
<li>Fresh Apples</li>
<li>Organic Bananas</li>
<li>Whole Wheat Bread</li>
</ul>
<h2>To-Do List for the Day</h2>
<ul>
<li>Complete coding challenge</li>
<li>Go for a walk in the park</li>
</ul>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in CSS Mastery
1Selector Mastery – Combination
IntroductionDescendant SelectorChild SelectorAdjacent Sibling SelectorGeneral Sibling SelectorRecap Challenge3Structural pseudo-classes
Structural pseudo-classesTargeting the First ChildTargeting the Last ChildPattern Power: Using nth-childRecap Challenge