I found this awesome css calc function from css-tricks
calc([minimum size] + ([maximum size] - [minimum size]) * ((100vw - [minimum viewport width]) / ([maximum viewport width] - [minimum viewport width])));
I try to use this calc function like this for margin-right
margin-right: calc(-20% + (0 - -20) * ((100vw - 320px) / (1600 - 320)));
I wanted to achieve the following:
-20% at 320px viewport width
0% at 1600px viewport width
The css calc function works perfectly with positive values, but apparently not with negative values. How do I change the calc function to work with percentages and negative values?
I tried this
margin-right: calc(-20% + (0% - -20%) * ((100vw - 320px) / (1600 - 320)));
but this is invalid.
Background
I am using this js function to calculate ranges
function _translateRange(
input,
inputMin,
inputMax,
outputMin,
outputMax
) {
let inputMinA = Math.min(inputMin, input);
let inputMaxA = Math.max(inputMax, input);
return (
outputMin +
((outputMax - outputMin) * (input - inputMinA)) /
(inputMaxA - inputMinA)
);
};
like this
translateRange(window.innerWidth, 320, 1400, -45%, 0%)
I want to convert this function to a css calc function. Why? Why do I not use the js function to calculate margin-right
? Because I want to do without as much js as possible in my application.
Note: This flexibility is especially important for me because I also want to work with as few media queries as possible.
Edit
I restructured my css code. I configure my absolute element, so i can use positive px values at begin and end with 0. So in this way, the css calc function works as i aspected.