I’m trying to get each child of a div translated a different percent:
#letters:nth-child(n){
transition: all 1s ease;
transform: translateX(calc(n*10%));
transition-delay: calc(n*200ms);
}
None of transform
and transition-delay
seems to work (the delay is equal for all the letters), but the value of transform
also returns an error `mismatched parameters (). How to fix it?
3
Answers
The issue with your code is that the
calc()
function needs numerical values. In your case, you’re usingn*10%
as an argument tocalc()
, but then
is not a numerical value with a unit. It represents the index of the child element, and you can’t use it directly in thecalc()
function. You can use css variables to store thetranslateX
values for each child element and then use those in the transform property. Like this:Hope this helps
There is no way to use the
n
fromnth-child()
as you intend in CSS as it is not a numerial value you can use incalc()
.The only way to achieve your aim (until the
sibling-index()
is implemented, see the answer by Temani Afif) is to manually set each child it’s own properties like this :You could use a CSS preprocessor to generate such code (ex: SCSS or LESS).
Here is what it could look like with SCSS :
That would generate the CSS for 50
.letters
elements.On a side note, your CSS code seems to imply you have several elements with the id
#letters
in your HTML. ids should be unique in a HTML document. That is why I used a class instead of id in my examples.In the near future (https://github.com/w3c/csswg-drafts/issues/4559#issuecomment-1642880894) you can do this: