July 22, 2024

/ ~

Apply style to the first child of the element

Selecting the element we want in CSS can be a bit troublesome.

Focus on the HTML below.

Terminal window
<div>
<h2>First sub header</h2>
<p>Content</p>
<h2>Second sub header</h2>
<p>Content</p>
</div>

If you want to select the first element of this, you can use first-child selector.

Terminal window
div {
*:first-child {
margin-top: 0;
}
}

If you only want to apply styling if the first element is h2, you can add a :is() selector.

Terminal window
div {
*:first-child:is(h2) {
margin-top: 0;
}
}