1

I have this example:

<div class="container">
    <div class="item-1"></div>
    <div class="item-2"></div>
    <div class="item-2"></div>
    <div class="item-2"></div>
    <div class="item-3"></div>
    <div class="item-3"></div>
</div>

... and the item-# could be as high as 48. What I want to do is target each unique .item-# and give it a different color.

I tried playing around with this in SCSS:

@for $i from 1 through 48 {
    .item-#{$i} { 
       &:nth-child(1):nth-last-child(2),
       &:nth-child(2):nth-last-child(1) { 
            color: red; } 
       }
}

... but it didn't work. I found a similar solution here: Can CSS detect the number of children an element has?, but the difference is that I need all .item-# to be wrapped in a single container.

I'd like to avoid using JavaScript.

Community
  • 1
  • 1
Titus Bartos
  • 33
  • 1
  • 5
  • If you have two classes that are the same how is that unique? – Adam Buchanan Smith May 13 '16 at 22:40
  • So in order for your for loop to be of any use, you need to change the background-color value in each iteration. Right now how you have it, you're creating 48 sets of styles that all set the color to red. Either set them all manually outside a for loop, or pass in some parameter that will change, eg `color: rgb(255, 255, $i * 50)`. Note that you should probably play around with those rgb values. – ingridly May 13 '16 at 23:21

1 Answers1

1

CSS does not provide the ability to match an element based on the number of siblings that match the same selector. See Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?

There are no pure CSS workarounds in the meantime.


Selectors 4's :nth-child(An+B of S) notation will provide this ability (annoyingly, there is no equivalent functional notation for :only-child() yet), but you still have to know the selector S in advance. That's where your SCSS will come in handy:

@for $i from 1 through 48 {
    :nth-child(1 of .item-#{$i}):nth-last-child(1 of .item-#{$i}) {
        // Styles
    }
}

Surprisingly, although Selectors 4 is still an unstable draft and no one aside from Safari has implemented this extension to :nth-child() yet, this will compile correctly with the current version of Sass. Of course, since it's not implemented, it's not actually going to work. Still, it's nice to know we'll be able to do this in the future (assuming Safari's implementation stays and everyone follows suit).

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356