how to make nth-child include a range (eg. 0-19)

hi all,

I have a bit of css code and each div child needs to have a property.

Hence it looks like this. It goes from 0 all the way to 19.

div:nth-child(0) { transform: translate3D(0%, 0%, calc(var(--itemZ) * var(--cameraSpeed) * 0 * -1px)); }
div:nth-child(1) { transform: translate3D(0%, 0%, calc(var(--itemZ) * var(--cameraSpeed) * 1 * -1px)); }
div:nth-child(2) { transform: translate3D(0%, 0%, calc(var(--itemZ) * var(--cameraSpeed) * 2 * -1px)); }
[...]
div:nth-child(17) { transform: translate3D(0%, 0%, calc(var(--itemZ) * var(--cameraSpeed) * 17 * -1px)); }
div:nth-child(18) { transform: translate3D(0%, 0%, calc(var(--itemZ) * var(--cameraSpeed) * 18 * -1px)); }
div:nth-child(19) { transform: translate3D(0%, 0%, calc(var(--itemZ) * var(--cameraSpeed) * 19 * -1px)); }

Is there a way that I can make it so it understands 0-19 in one line only?

Any ideas?

Using just CSS, that is a bit tricky. Are you looking for a pure CSS-only solution, or would you be ok with a little bit of JavaScript thrown in there?

:slight_smile:

sure

Or sass?

https://jsfiddle.net/41ykz0se/

One approach would be to make your style rule look like this:

div {
  transform: translate3D(0%, 0%, calc(var(--itemZ) * var(--cameraSpeed) * var(--count) * -1px));
}

Notice that I added a variable called --count to represent 0, 1, 2, …, 19. On each div, you can programmatically set the --count variable. This tutorial covers how to do that: https://www.kirupa.com/html5/css_variables_js_win.htm

By setting the count value on each div element, that will carry over into the appropriate value you will need. Does this make sense? I am kinda rushing the explanation while I am wrapping something else up :stuck_out_tongue:

1 Like

I was hoping that attr() would work in this context too so count could be set in the html and not through JS, but it looks like its not that well supported yet.

That was my first thought, but it didn’t work for browser support reasons like you mention :chart:

I wonder if this person will ever be back? I find it rather amazing on how many forums this question was actually asked. Interestingly here at Kirupa it seemed to yeild the most discussion, so nice job peeps. :+1:

Whoa, dude on SO showing you can set vars in style attributes… which I guess makes sense.

<div style="--counter: 19;">19</div>

but that would get around the attr() limitation.

Yes I too liked that aspect when I saw it on SO. You could couple it with a bit of JS and dynamically create and style the divs.

1 Like

i had this problem before thank u guys