Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculating transform CSS params depending on the child's index

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There is no way to use the n from nth-child() as you intend in CSS as it is not a numerial value you can use in calc().
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 :

.letters:nth-child(1){
    transition: all 1s ease;
    transform: translateX(calc(1*10%));
    transition-delay: calc(1*200ms);
}

.letters:nth-child(2){
    transition: all 1s ease;
    transform: translateX(calc(2*10%));
    transition-delay: calc(2*200ms);
}
...

You could use a CSS preprocessor to generate such code (ex: SCSS or LESS).
Here is what it could look like with SCSS :

$letters : 50;

@for $i from 1 through $letters {
  .letters:nth-child(#{$i}) {
    transition: all 1s ease;
    transform: translateX($i*10%);
    transition-delay: $i*200ms;
  }
}

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading