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

I have the following code that works fine with centering my content until vh is less than 650px . I was wondering if the way to make this value never fall below 0 only with CSS calc .

 .my-margin-top { margin-top: calc(50vh - 325px); } 
+8
css css3 css-calc
source share
2 answers

Assuming there is no way to bind the values ​​computed with calc() , you can use a media query if max-height no more than 650px

 .my-margin-top { margin-top: calc(50vh - 325px); } @media all and (max-height: 650px) { .my-margin-top { margin-top: 0; } } 

or you can also return logic by wrapping an existing rule in min-height mediaquery

 @media all and (min-height: 650px) { .my-margin-top { margin-top: calc(50vh - 325px); } } 
+15
source share

To answer a general question:

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

The answer is no, because CSS does not provide a way to manually limit (or pinch) the amount to the minimum or maximum value.

Regardless of whether a number or length can be limited to a limited range, it depends on the property that this calc() value has. From spec :

The value obtained from the expression must be clamped to a range that is valid in the target context.

These two equivalents are 'width: 0px', since widths less than 0px are not allowed.

 width: calc(5px - 10px); width: 0px; 

For example, while negative values ​​for margin and z-index valid, negative values ​​for border-width , padding , height , width , etc. not. Their specificity is almost always determined in the specification for the corresponding property.

As you seem to be using view units in your example, you can use media queries in conjunction with them as demonstrated by fcalderan .

+3
source share

All Articles