Skip to content Skip to sidebar Skip to footer

Sizing Elements Based On The Number Of Siblings In A Single Container Scss

I have this example:

Solution 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).

Post a Comment for "Sizing Elements Based On The Number Of Siblings In A Single Container Scss"