Search code examples
htmlcsscss-calc

How to avoid negative values from css calc function?


I am using css calc function from css-tricks

calc([minimum size] + ([maximum size] - [minimum size]) * ((100vw - [minimum viewport width]) / ([maximum viewport width] - [minimum viewport width])));

I use the calc function like this

margin-top: calc(270px + (0 - 270) * (100vw - 320px) / (900 - 320));

This works and my margin-right is 270px at 320px viewport width and 0px at 900px viewport width. But when I resize my window bigger than 900px, the margin-right is negative.

I can use media queries, but is there another CSS solution? Can I combine these calc function with min() max() or clamp() to avoid negative values?

Edit

i found a possible solution. It works with max() in this way

margin-right: max(0vw, calc(270px + (0 - 270) * ((100vw - 320px) / (900 - 320))))

Solution

  • for all who are interested. I ended up with this css rules.

    if your minimum value is negative you need the css min() function like this

    margin-right: min(0vw, calc(-270px + (0 - -270) * ((100vw - 320px) / (900 - 320))))
    

    if your minimum value is positive you need the css max() function like this

    margin-right: max(0vw, calc(270px + (0 - 270) * ((100vw - 320px) / (900 - 320))))