Meek Meek - 5 months ago 8
CSS Question

Target :first-child or :nth-of-type(1)

I need to target the first element inside other elements, but somehow it's not as easy. Say I have this html:

<div id="sidebar">
<div class="right">
<div class="container-right">
<div class="freetext">
<h2>heading - target me</h2>
<p>Text</p>
</div>
<div class="freetext">
<h2>Heading</h2>
<p>Text</p>
</div>
</div>
</div>
</div>


- and I just want to target the first h2 in that sidebar. How can I do that? I have tried with first-child and nth-of-type, but it's not working. See fiddle here.

Answer

You need to target first-child of parent div of h2.

#sidebar > div > div > div:first-child > h2 {
    color: blue;
}

Or:

#sidebar div.freetext:first-child > h2 {
    color: blue;
}

<div id="sidebar">
    <div class="right">
        <div class="container-right">
            <div class="freetext">
                <h2>heading - target me</h2>
                <p>Text</p>
            </div>
            <div class="freetext">
                <h2>Heading</h2>
                <p>Text</p>
            </div>
        </div>
    </div>
</div>

jsFiddle here