CSS transform - translate

I am a bit baffled about how the translate method works.
I watched some tutorials on making an image slider, and in order to move the images horizontally, they wrote this code:

index = 1;
const width = image[index].clientWidth; 

images.style.transform = `translateX(${-width * index}px)`;

It doesn’t make sense to me why * index is included, and not just -width, because this is within a transitionend listener, which means upon each transitionend, the image moves one to the left. So if it’s just one image width that is moving, why are we multiplying by the index which increases at every transition?

For example if the index is 2, then it would translate by width * 2, but then doesn’t that mean it should move by two images not one?

It’s very hard to tell without seeing how the slider code is structured (HTML and CSS and JS) but if there are multiple images, and they sit next to each other, then to translate them to the correct position in the row it has to be the width of the image * the position in the row (so the index)

1 Like

Thanks yep that’s basically what I was asking - why does it have to be multiplied by the position in the row? For example if width is 200px, then you do 200 * 2 - that would be 400, then wouldn’t it move 400px which means it moves 2 images? Sorry maybe overthinking it but just not getting the inner workings of this

Yes, you’ve got it right. But if it’s index 0 (first item) it translates 0, index 1 translates 200, index 2 translates 400

1 Like

So does that mean the starting point of when we translate each image is always the same starting point, ie 0px?
I’m confused bc I just assumed after moving the first image, the starting point would be the width of that image ie 200px and then if you move it width*index again wouldn’t it move 400px so then it would skip an image?

Translations are applied based on the element size/position itself. The starting point in this case doesn’t change. So center an image means 0, one to the left is -200, two to the left is -400, three to the left is -600 and so on

1 Like

I think I get it, thanks for explaning :pray: