July 22, 2024 /
1 min /
#css
#selectors
#styling
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.
<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.
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.
div { *:first-child:is(h2) { margin-top: 0; }}