CSS select first and second child elements
CSS Select First and Second Child Elements
In web development, we often need to style or manipulate elements on the page. CSS selectors allow us to easily select specific elements and perform manipulations on them. In this article, we’ll explore how to use CSS selectors to select the first and second child elements.
Selecting the First Child
To select the first child element, we can use the :first-child
pseudo-class selector. This selector selects the first child of a parent element and applies styles to it.
The sample code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select the first child element</title>
<style>
ul li:first-child {
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li>First child element</li>
<li>Second child element</li>
<li>Third child element</li>
</ul>
</body>
</html>
In the above code example, we apply styles to the first li
child element of the ul
element, making its text blue and bold.
Running Results
When we open the above code example in a browser, we see that the text of the first child element becomes blue and bold, while the text of the other child elements remains unchanged.
Selecting the Second Child
To select the second child, we can combine the :first-child
pseudo-class with the +
adjacent sibling selector. First, we use :first-child
to select the first child, and then use the +
adjacent sibling selector to select the first child’s adjacent sibling, which is the second child.
Sample code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Select the second child element</title>
<style>
ul li:first-child + li {
color: red;
font-style: italic;
}
</style>
</head>
<body>
<ul>
<li>First child element</li>
<li>Second child element</li>
<li>Third child</li>
</ul>
</body>
</html>
In the example code above, we style the second child by selecting the first li
child using :first-child
and then selecting the first child’s adjacent siblings using the +
selector to make its text red and italic.
Running Results
When we open the sample code above in a browser, we see that the text of the second child element turns red and italicized, while the other child elements remain unchanged.
Through the above example, we can see how to select the first and second child elements in CSS and apply styles to them. In actual development, we can flexibly use these selectors to optimize page style and layout, making the page more beautiful and easy to read.