Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select nth-child across multiple parents

I have the following markup:

<div class="foo">
    <ul>
        <li>one</li>
        <li>two</li>
    </ul>
    <ul>
        <li>three</li>
    </ul>
    <ul>
        <li>four</li>
    </ul>
</div>

I wish to style "one" and "three".

However, the markup could also be:

<div class="foo">
    <ul>
        <li>one</li>
        <li>two</li>
        <li>three</li>
    </ul>
    <ul>
        <li>four</li>
    </ul>
</div>

I've tried using the following CSS:

.foo li:nth-child(1),
.foo li:nth-child(3)
{
    color:red;
}

However, as expected, this is styling the first child of each ul. (Demo: http://jsfiddle.net/hTfVu/)

How can I change my CSS so that I can target the 1st and 3rd li belonging to .foo?

like image 867
Curtis Avatar asked Jul 15 '13 10:07

Curtis


People also ask

How do I choose a multiple nth child?

Definition and Usage The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

How do I select all 3 children in CSS?

formula (an + b) nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one. Multiplication and division are not supported in nth-child(n) formulas.

How do you target the nth child in SCSS?

Writing Complex :nth-child() Selectors It works exactly the same as :nth-child except that it starts from the end of the parent. For example, you can select the first three children of a parent by using the selector :nth-child(-n + 3) . You can use :nth-last-child(-n + 3) to select the last three.

How do I select a specific child in CSS?

The child combinator ( > ) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Elements matched by the second selector must be the immediate children of the elements matched by the first selector.


1 Answers

You can't do that with CSS selectors alone. :nth-child() and sibling combinators are limited to children/siblings sharing the same parent only, as implied by their names, and CSS selectors cannot account for such variations in parent-child structure, nor is there anything like an :nth-grandchild() selector (even :nth-match() from Selectors 4 limits itself to elements sharing the same parent only).

Of course with something like jQuery it becomes trivial: $('.foo li:eq(0), .foo li:eq(2)') Otherwise you'll have to mark the first and third li elements explicitly using classes or IDs, and then select them.

like image 138
BoltClock Avatar answered Oct 07 '22 23:10

BoltClock