CSS selects the first element of a child element

CSS Select the First Child Element

CSS Select the First Child Element

In CSS, we often need to select the first child element of a parent element for styling. In this article, we’ll discuss in detail how to use CSS selectors to select the first child element, demonstrating this with code examples.

Selecting Child Elements with CSS

In HTML, a parent element often contains multiple child elements, and you may want to style only the first child. This is achieved using the CSS child selector >.


Syntax

The syntax of the child selector is as follows:

parent element > child element {
/* style settings */ 
} 

Where, > selects the direct child elements of the parent element.

Example

Let’s use an example to demonstrate how to use the child selector to select the first element. Suppose we have the following HTML structure:

<div class="parent">
<p>First-child</p>
<p>Second-child</p>
<p>Third-child</p>
</div>

Now, we want to select the first p element under .parent and set its text color to red. We can write CSS code like this:

.parent > p:first-child {
color: red;
}

This will select the first p element under .parent and set its text color to red.

Running Results

If we put the above HTML structure and CSS styles into an HTML file and run it in a browser, the result will be similar to the following:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Selecting the First Child Element Example</title>
<style>
.parent > p:first-child {
color: red;
}
</style>

</head>

<body>
<div class="parent">
<p>First Child</p>
<p>Second Child</p>
<p>Third Child</p>
</div>

</body>
</html>

Opening this HTML file in a browser, we can see that the text color of the first child element has indeed changed to red.

Summary

By using the CSS child selector >, we can easily select the first child element of a parent element for styling. Such selectors are often used in actual projects and can help us more precisely control the styles of page elements.

Leave a Reply

Your email address will not be published. Required fields are marked *