Lorenzo Marcon
Lorenzo Marcon

Reputation: 8169

:first-child selector selects more than one children

I'm trying to apply a style to ONLY the very first child of an element. I'm using :first-child in the css to achieve this, but it looks like it's not the behaviour I'm looking for.

Take the following markup as example:

<ul class="myUl">
    <ul class="mySubUl">
        <li>foo0</li>
        <li>foo1</li>
    </ul>
    <ul class="mySubUl">
        <li>foo2</li>
        <li>foo3</li>
    </ul>
</ul>
======================
<ul class="myUl">
    <li>foo0</li>
    <li>foo1</li>
    <ul class="mySubUl">
        <li>foo2</li>
        <li>foo3</li>
    </ul>
</ul>

and this simple CSS:

ul.myUl li:first-child {
    color: red;
}

Live fiddle: http://jsfiddle.net/bsSDh/1/

This applies not only to the first child of the ul.myUl elements, but also to the first child of ul.subUl. I would have expected this behaviour if the CSS selector was ul li:first-child (which works), but since I'm adding a class to the selector I'm expecting to apply that style only to the very first child.

Why does the style applies not only to the first child? Am I missing something about first-child specs or using the selector in the wrong way?

Upvotes: 1

Views: 1951

Answers (3)

Sirko
Sirko

Reputation: 74046

I think you need an additional child selector element like this:

ul.myUl > li:first-child {
    color: red;
}

Example Fiddle

Your selector selects any <li> below ul.myUL, that is a first child. As this references only to the immediate parent and not any other ancestor, all those other <li> match as well.

EDIT

After your comment, I assume, that you will need a somehow complexer selector like this:

ul.myUl > li:first-child,
ul.myUl > ul:first-child > li:first-child {
        color: red;
}

Upvotes: 5

Andrea Ligios
Andrea Ligios

Reputation: 50203

Pay attention to the differences between the Child Combinator (a direct child) and the Descendant Combinator (any element contained).

You should use this two selectors to achieve the result wanted on the two known cases:

ul.myUl > ul:first-child > li:first-child {
    color: red;
}

ul.myUl > li:first-child {
    color: red;
}

Running Demo

Upvotes: 0

Howard
Howard

Reputation: 39197

The selector

ul.myUl li:first-child

selects any li:first-child below any ul.myUl (i.e. first child of any parent inside the ul). Instead you might want to select a direct child via

ul.myUl > li:first-child

or even

ul.myUl > ul.subUl:first-child > li:first-child

Upvotes: 1

Related Questions