I'm trying to make a css class that would give a background color to the first found element with a specific tag..
This CSS
.blue p:first-of-type {
    background-color:#2E9AFE;
}
Works for example 1:
<div class="blue">
    <p>element 1</p>
    <p>element 2</p>
    <p>element 2</p>
</div>
Doesn't work for example 2:
<div class="blue">
    <ul>
        <li><p>Parent 1</p>
            <ul>
                 <li><p>Element 1.1</p></li>
                <li><p>Element 1.2</p></li>
            </ul>
        </li>
    </ul>
</ul>
In example 2, first element with tag p is Parent 1, however my code colors every element. Why?
Fiddle: http://jsfiddle.net/alexix/CYX32/1/
The :first-of-type selector selects the first of type contained within its parent element. In each case, the p is the first of type within their li elements.
If you wish to select the first of type p within the first of type li within the first of type ul you're going to have to use the following selector:
.blue > ul:first-of-type > li:first-of-type > p:first-of-type {
    background-color:#2E9AFE;
}
JSFiddle demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With