CSS Linear Interpolation Map Range Function Math
Starting Square
Let's say you have a square and a slider that changes its size. It's trivial to make happen by using slider's value to set both the width and height of the square. Here's one that's 50 pixels per side at its smallest and 200 when it's fully grown.
Output
HTML
Square Size:
-
CSS
}
}
window. =
Changing Shape
Works great. But, what if you wanted to start with a square and end up with a rectangle? That's where Linear Interpolation (LERP)1 comes. It lets you create a map between two ranges. Feed it the position in one range and it gives you the corresponding value for the other.
For example, if we want to start with the same 50x50 pixel square, but end up with a 400x100 pixel rectangle we know that:
- When our slider is all the way down (i.e. at 0%), both values should be 50.
- When our slider is all the way up (i.e. at 100%), the width should be 400 and the height should be 100.
The Linear Interpolation gives us all the values in between. Here's what the CSS looks like:
CSS
}
It's pretty gnarly, but that's what copy/paste is for. Just fill in the input values and update the -- with the raw number for your x value. Then, use the -- and -- output values wherever you need them. As long as the values work with the CSS ) function you're all set.
Here's what it looks like in action:
Output
HTML
Current Width:
-
window. =
CSS
}
Happy Sizing
It took me a while to find the LERP math when I was first looking for it. I was doing a JavaScript project at the time. I figured I might as well make a CSS version since I already had the math.
I expect I'll use JavaScript most of the time. But, it's nice to know doing it directly in CSS is an option.
Enjoy,
-a
Endnotes
The JavaScript on this page uses bitty to wire things up. It's a little single file web component that adds interactive to pages. Check it out if you're into that kind of thing:
This is the CSS version of the Linear Interpolation (LERP) Math function I set up in JavaScript in A JavaScript Linear Interpolation Map Range Function Thing
Footnotes
The math that I'm glad someone else figured out.