Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css select first element with specific tag [duplicate]

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/

like image 851
Alexandru Severin Avatar asked Dec 15 '22 22:12

Alexandru Severin


1 Answers

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.

like image 163
James Donnelly Avatar answered Dec 17 '22 11:12

James Donnelly