I'm trying to achieve a constant transition speed.
Note, I don't mean the difference between "ease" and "linear". What I mean is if we go from 0px to 20px it will take 1 second, but going from 0 to 100px should take 10 seconds.
.box {
width: 0px;
height: 20px;
transition: width 1s linear;
}
Can't seem to find a way to do this. And all my searches just turn up ease/linear differences.
.
The best way I've found is using custom properties. In the following example, I'm using 20
to represent one unit of width. When multiplied by .05
we get 1
, or a single second. Using a custom property, we can override the transition-width
variable to a desired pixel length. The calculation will update dynamically and adjust the transition-duration
accordingly.
setTimeout(() => {
document.querySelector('.box.one').classList.add('start');
document.querySelector('.box.two').classList.add('start');
}, 0);
.box {
--transition-width: 20;
--transition-speed: .05;
width: 0px;
overflow: hidden;
height: 20px;
transition-property: width;
transition-timing-function: linear;
transition-duration: calc(var(--transition-width) * var(--transition-speed) * 1s);
background: black;
}
.box.one.start {
width: 20px;
}
.box.two.start {
--transition-width: 100;
width: 100px;
}
<div class="box one"></div>
<div class="box two"></div>