Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make CSS calc() never be a negative value?

Tags:

css

css-calc

I have the following code which works great with centering my content until the vh is less then 650px. I was wondering if there was a way to make this value never go below 0 only using CSS calc.

.my-margin-top {
    margin-top: calc(50vh - 325px);
}
like image 925
cmorrissey Avatar asked Feb 24 '16 15:02

cmorrissey


People also ask

How does the CALC () function work on values in CSS?

The calc() function takes a single expression as its parameter, with the expression's result used as the value. The expression can be any simple expression combining the following operators, using standard operator precedence rules: + Addition.

Can you use Calc for padding CSS?

A solution for you would be to use CSS calc, it has good browser support and fixes your issue in quite a simple manner. The only downside here is that it doesn't calculate the padding-top in % but you simply cannot calculate padding-top in % from the height of the element unless you use javascript.

What are negative CSS values?

It is possible to give margins a negative value. This allows you to draw the element closer to its top or left neighbour, or draw its right and bottom neighbour closer to it.


1 Answers

In the latest browser versions there is max() function in CSS:

.my-margin-top {
    margin-top: max(50vh - 325px, 0);
}

Browser compatibility: Firefox 75+, Chrome/Edge: 79+, Safari: 11.1+

There is also clamp(): clamp(0, 50vh - 325px, 100vh), where 100vh is an upper bound. But this is not in Safari yet, although can be simulated with min() and max() calls.

like image 188
user Avatar answered Sep 22 '22 15:09

user