Css first-of-type under another class
I have a html file that looks something like this:
<div class="my_class">
<h1>gets styled and that good</h1>
<h1>doesn't get styled and this is intended</h1>
<div class="my_other_class">
<h1>but this also get styled, but shouldn't</h1>
</div>
</div>
<div class="my_class">
<h1>do style</h1>
<h1>don't style</h1>
<div class="my_other_class">
<h1>shouldn't but does</h1>
</div>
</div>
now i use .my_class h1:first-of-type {...}
to create the first one h1
. However, the third also gets style and shouldn't.
Is there a way to select only the first one h1
?
+3
source to share
4 answers
Use child selector : >
:
.my_class > h1:first-of-type {...}
.my_class > h1:first-of-type {
color: red;
}
<div class="my_class">
<h1>gets styled and that good</h1>
<h1>doesn't get styled and this is intended</h1>
<div class="my_other_class">
<h1>but this also get styled, but shouldn't</h1>
</div>
</div>
<div class="my_class">
<h1>do style</h1>
<h1>don't style</h1>
<div class="my_other_class">
<h1>shouldn't but does</h1>
</div>
</div>
+5
source to share
Use a combinator for kids >
.
.my_class > h1:first-of-type {
color: red;
}
<div class="my_class">
<h1>gets styled and that good</h1>
<h1>doesn't get styled and this is intended</h1>
<div class="my_other_class">
<h1>but this also get styled, but shouldn't</h1>
</div>
</div>
+9
source to share
Another approach would be to use a pseudo-element :first-child
:
.my_class > h1:first-child {
color: red;
}
p {
font-size:2em;
}
div div {
margin-left:50px;
}
<p>Main Div 1</p>
<div class="my_class">
<h1>gets styled and that good</h1>
<h1>doesn't get styled and this is intended</h1>
<p>Sub Div 1</p>
<div class="my_other_class">
<h1>but this also get styled, but shouldn't</h1>
</div>
</div>
<p>Main Div 2</p>
<div class="my_class">
<h1>do style</h1>
<h1>don't style</h1>
<div class="my_other_class">
<h1>shouldn't but does</h1>
</div>
</div>
0
source to share