cmorrissey cmorrissey - 2 months ago 6
CSS Question

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

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);
}

Answer

Premising that there's no way to bound the values computed by calc() you could use a mediaquery when max-height is at most 650px

.my-margin-top {
    margin-top: calc(50vh - 325px);
}

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

or you might also revert the logic by wrapping the existing rule into a min-height mediaquery

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