CSS select first child element
CSS Select First Child
In CSS, you can use pseudo-class selectors to select specific child elements of an element. Among them, the :first-child
pseudo-class selector is used to select the first child element of the specified element.
Grammar
:first-child
The syntax of the pseudo-class selector is as follows:
selector:first-child {
/* styles */
}
Where selector
is the selector of the parent element to be selected, :first-child
is a pseudo-class selector used to select the first child element of the parent element.
Example
Assume the following HTML structure:
<div class="parent">
<p>First child</p>
<p>Second child</p>
<p>Third child</p>
</div>
To select the first child of the .parent
element, use the following CSS style:
.parent p:first-child {
color: red;
}
The above code selects the first p
element under the .parent
element and sets its text color to red.
Running Results
According to the above example code, the text color of the first child element will be set to red, while other child elements retain their default styles. The actual effect is as follows:
- First child element (the first
p
element): text color is red - Other child elements (the second and third
p
elements): retain their default styles
Notes
- When using the
:first-child
pseudo-class selector, note that it selects the first child of the parent element that meets the selector criteria, not the first element in the entire document. - To select the first specific child of a parent element, you can combine selectors flexibly. For example,
.parent p:first-child
selects the firstp
child of the.parent
element.
In summary, this article detailed how to use the CSS :first-child
pseudo-class selector to select the first child of a parent element, and provided example code and runtime results.