How do I target direct child h2 of div but at the same time make sure any other h2 doesn’t get changed.
At one place I have this markup.
<div class="cms-page-view">
<div class="column">
<div></div>
<div></div>
<div>
<h2>Hello</h2> <!-- Target this -->
<p>Some Text</p>
</div>
</div>
</div>
And at another place, I have this markup.
<div class="cms-page-view">
<div class="column">
<div></div>
<div></div>
<div>
<section>
<div>
<h2>Hola</h2> <!-- Make sure this does not change -->
<p>Some Text</p>
</div>
</section>
</div>
</div>
</div>
Is there any way to do this without using :first-child or :nth-child().
I tried this but it doesn’t work:
.cms-page-view {
& .column {
& div {
& > h2 {
color: blue;
}
}
}
}
>Solution :
Assuming you can’t touch your HTML, you can use > multiple times to achieve the result you want
SNIPPET
.cms-page-view .column > div > h2 {
background: red
}
/* SASS
.cms-page-view {
& .column {
& > div {
& > h2 {
background: red;
}
}
}
}
*/
<div class="cms-page-view">
<div class="column">
<div></div>
<div></div>
<div>
<!-- Target this -->
<h2>Hello</h2>
<p>Some Text</p>
</div>
</div>
</div>
<div class="cms-page-view">
<div class="column">
<div></div>
<div></div>
<div>
<section>
<div>
<!-- Make sure this does not change -->
<h2>Hola</h2>
<p>Some Text</p>
</div>
</section>
</div>
</div>
</div>