Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:nth-child(2n) of [attribute=value]

I have a list with rows, each li has an attribute data-status which the value can be 1-5:

<ul>
    <li data-status="1"></li>
    <li data-status="2"></li>
    <li data-status="2"></li>
    <li data-status="1"></li>
    <li data-status="1"></li>
    <li data-status="2"></li>
    <li data-status="3"></li>
    <li data-status="4"></li>
    <li data-status="5"></li>
    <li data-status="5"></li>
    <li data-status="1"></li>
</ul>

I want each odd li that the data-status is 1 to be have a different background, is it possible to do in CSS?

like image 591
user2436448 Avatar asked May 30 '13 12:05

user2436448


1 Answers

If the question is how to select all the odd elements with a particular attribute ?, then it is possible how explained in the other answers, with

li[data-status="1"]:nth-child(2n+1) {
   background: #f00;
}

or in an even easier way:

li[data-status="1"]:nth-child(odd) {
   background: #f00;
}

Take a look at this good article on how nth-child works.

If, instead, the question is how to select all the elements with a particular attribute, and then pick only the odd of that sub-list ? , well, that is not yet possible with CSS, but it will with CSS Selectors Level 4, as explained here, with the nth-match() pseudo-class:

:nth-match(An+B of <selector>)

that in your case would be

li:nth-match(2n+1 of [data-status="1"])

or

li:nth-match(odd of [data-status="1"])

Let's wait... CSS4 is coming !! :P


EDIT: as reported by Michael_B, this feature has been stripped by CSS4 specifications, so stop waiting and start figuring another way to do it :/

like image 155
Andrea Ligios Avatar answered Oct 16 '22 22:10

Andrea Ligios