Negative vw value is not recognized in translateX(-100vw)

866 Views Asked by At

I am using css transitions and a little javascript to make elements slide into the page from the left or right.

It works perfectly fine from the right side (starting from transform: translateX(100vw);). But from the left side (negative translate value: transform: translateX(-100vw);) it does not work at all. There is no error, but the element pops up at the end of the transition without any "animated" movement.

Using a px value instead of vw for the negative/ left side also works fine. I found several examples where people used negative vw values and did not seem to have problems with it...

I also tried transform: translateX(calc(0px - 100vw));. No luck...

(I am not using any libraries etc.)

<!-- HTML -->

<div class="container">
  <div class="slide-in l"></div>
  <div class="slide-in r"></div>
</div>
/* CSS */

.slide-in {
  transition: transform 0.8s ease;
}
.slide-in.l {
  transform: translateX(-100vw); /* this is the line does not work */
}
.slide-in.r {
  transform: translateX(100vw);
}
.slide-in.show {
  transform: translateX(0);
}
/* JavaScript */

const slider = document.querySelectorAll('.slide-in');

window.addEventListener("load", () => {
    slider.forEach(s => {
        s.classList.add('show');
    })
});

Any ideas what could be the problem?

1

There are 1 best solutions below

1
Lars On

The translateX(-100vw); should work fine.
When you run this snippet you should see both rectangles sliding into view, the green one from the left and the right one from the right.

const slider = document.querySelectorAll('.slide-in');

window.addEventListener("load", () => {
  slider.forEach(s => {
    s.classList.add('show');
  })
});
/* CSS */

.slide-in {
  transition: transform 0.8s ease;
  width: 100px;
  height: 100px;
}

.slide-in.l {
  transform: translateX(-100vw);
  /* this is the line does not work */
  background-color: green;
}

.slide-in.r {
  transform: translateX(100vw);
  background-color: blue;
}

.slide-in.show {
  transform: translateX(0);
}
<!-- HTML -->

<div class="container">
  <div class="slide-in l">a</div>
  <div class="slide-in r">b</div>
</div>