Julian Lettner
Julian Lettner

Reputation: 3669

Select nth element for elements that do not share the same immediate parent

How do I select the 4th (or any specific) li element in the following HTML structure? Is this even possible? (From my understanding :nth-child and :nth-of-type require the elements to be siblings.)

<div>
    <ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Pear</li>
    </ul>
    <ul>
        <li>Melon</li>
        <li>Mango</li>
    </ul>
    <ul>
        <li>Strawberry</li>
    </ul>
</div>

The above structure is dynamic, so I don't know how many ul elements there are nor how many li elements each of them contains. Is there still a way to select the nth li element on the page?

JsFiddle: click

I am using LESS. Is there something in LESS that could help me?

Update:
I just found the :nth-match CSS4 pseudo class which is not (yet) supported: CSS nth-match doesn't work
This and your comments/answers confirm my belief that it is not possible today... :(

Upvotes: 1

Views: 488

Answers (2)

Craig Wayne
Craig Wayne

Reputation: 5070

AFAIK (and i've been with my css friend for around 4 years now)

you can't create css rules based on the content of a tag... with that said however.... have a look at this:

link

the basic idea is dont add the content to inside the tag, but rather as a tag attribute like so:

<li value="some_number"></li>

then in your css

li:before{
 content:attr(value);
}

then you can target it as follows:

li[value="4"]{
 background-color:red;
}

and a quick CanIUse search shows that the "attr" css technique is not support by ANY version of IE (sorry):

link:

Upvotes: 0

Etheryte
Etheryte

Reputation: 25327

Since :nth-child and other similar selectors make matches based on sibling elements and CSS has no parent-wise selectors this isn't possible.
Less is simply a language that is compiled into CSS, it doesn't actually add any new features into CSS.
The easy alternative is to use Javascript.

Upvotes: 2

Related Questions