Apply a style to the first child in an element in CSS
Jul 22, 2024/
#css
/-1 minSelecting the element we want in CSS can be a bit troublesome.
Focus on the HTML below.
1<div>
2 <h2>First sub header</h2>
3 <p>Content</p>
4 <h2>Second sub header</h2>
5 <p>Content</p>
6</div>
If you want to select the first element of this, you can use
first-child
selector.
1div {
2 *:first-child {
3 margin-top: 0;
4 }
5}
If you only want to apply styling if the first element is
h2
, you can add a :is()
selector.
1div {
2 *:first-child:is(h2) {
3 margin-top: 0;
4 }
5}