11

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?

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
user2436448
  • 445
  • 4
  • 7
  • 18

3 Answers3

18

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 :/

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • I just checked [**Selectors 4 spec**](https://drafts.csswg.org/selectors-4/). There is nothing called `nth-match()` defined therein. Maybe it was removed? Whatever the case, it doesn't exist. – Michael Benjamin Feb 13 '16 at 03:07
  • Ah, on further review, it was removed from the spec: http://stackoverflow.com/a/31415015/3597276 – Michael Benjamin Feb 13 '16 at 03:10
  • @Michael_B I knew this happened, but I forgot to come here updating the answer (and probably there are another couple of answer of mine to update)... I've did it now, thank you – Andrea Ligios Feb 14 '16 at 23:51
  • @AndreaLigios, I was really hoping your answer worked! As I'm trying to craft an answer for this question: http://stackoverflow.com/q/35355253/3597276 ... Cheers! – Michael Benjamin Feb 15 '16 at 01:23
2

I believe you can do

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

There's a working example at http://jsfiddle.net/adamh/ggtff/

Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99