For example I have this code:
<div class="main-element">
<h4>Title 1</h4>
<ul>
<li></li>
<li></li>
<li>
<h4>Title2</h4>
</li>
</ul>
</div>
I want to select and use the same styling on all h4 elements but I also want to put additional styles on the first one. for example I want all h4 element’s margin-top and margin-bottom to have the value of 8px, but for the first h4 element I want their margin-top to have the vaule of 0.
I’ve tried to use the :first-child and first-of-type selectors. for example:
.main-element h4 {
color: blue;
}
.main-element h4:first-of-type {
color: red;
}
It colors all elements red instead of only the first one.
2
Answers
first-of-type
will be true for bothh4
‘s since the second one is inside a<li>
, which makes is the first child again.Consider adding classes to the one you wish to style
first-of-type
always relates to the current parent, i.e it means "first occurrence of this type within this container". So your.main-element h4:first-of-type
matches every h4 that is a descendant ofmain-element
and is the first h4 in its parent.If you want to style only the one that’s a direct child of the parent, you can use the ">" selector, like: