How to avoid negative values from css calc function?
Asked Answered
T

1

6

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))))
Tamaratamarack answered 13/10, 2020 at 16:23 Comment(2)
why dont you adjust it with media query to adjust your calcul ?Hognut
@Hognut i want to use as few media queries as possible in my project and it tears me apart to combine the css functions perfectly, if possible, so that you can do without for example media queries in some cases.Tamaratamarack
T
3

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))))
Tamaratamarack answered 13/10, 2020 at 17:5 Comment(1)
You welcome for correction and giving you answer...Hognut

© 2022 - 2024 — McMap. All rights reserved.