Home > Software engineering >  :first-of-type doesn't work the way it should
:first-of-type doesn't work the way it should

Time:03-20

I'm having trouble understanding why :first-of-type class works for all types, not just the first one. Here's my example code

**<style>
    .garden ol:first-of-type li {
        color: green;
    }
</style>**


<ul >
    <div>Garden</div>
    <li>Fruit:
        <ol>
            <li>One</li>
            <li>Two</li>
            <li>Three</li>
        </ol>
    </li>
    <li>Vegies:
        <ol>
            <li>One</li>
            <li>Two</li>
            <li>Three</li>
        </ol>
    </li>
</ul>

The result is that both OLs are colored in green. If I try using :nth-of-type(1) - nothing is colored If I try using :nth-of-type(2) - both OLs are colored again

What I am doing wrong?

CodePudding user response:

Both ol elements are the first of their type (ol) inside their respective parent elements (two different li elements).

If you are trying to target the ol inside the first li inside the ul then you can use that li since it is the first of its type.

.gardern > li:first-of-type li 

Note that div elements are not allowed to be children of ul elements.

  • Related