有没有办法让 CSS calc() 永远不会是负值?

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

我有以下代码,它非常适合将我的内容居中,直到 vh 小于 650px。我想知道是否有办法让这个值永远不会低于 0 仅使用 CSS calc.

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

前提是无法限制 calc() 计算的值,当 max-height 最多为 650px

时,您可以使用媒体查询
.my-margin-top {
    margin-top: calc(50vh - 325px);
}

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

或者您也可以通过将现有规则包装到 min-height 媒体查询

中来还原逻辑
@media all and (min-height: 650px) {
   .my-margin-top {
       margin-top: calc(50vh - 325px);
   }
}

回答一般问题:

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

答案是否定的,因为 CSS 不提供手动将数量限制(或固定)到某个最小值或最大值的方法。

一个数字或长度是否可以原生限制在一定范围内取决于具有这个calc()值的属性。来自 spec:

The value resulting from an expression must be clamped to the range allowed in the target context.

These two are equivalent to 'width: 0px' since widths smaller than 0px are not allowed.

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

例如,虽然 marginz-index 的负值有效,但 border-widthpaddingheight、[=17 的负值有效=] 等等都不是。这些细节几乎总是在各自的规范中定义 属性.

由于您碰巧在示例中使用了视口单位,因此您可以将媒体查询与它们结合使用,如

你也可以使用这个技巧: calc((#{$gap} + 1.5rem) / -1); 将导致 calc(-32px + -1.5rem)

在最新的浏览器版本中 CSS 中有 max() 功能:

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

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

还有 clamp(): clamp(0, 50vh - 325px, 100vh), where 100vh is an upper bound. But this is not in Safari yet,虽然可以用 min()max() 调用来模拟。

你可以这样做:

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

将您的计算结果乘以 -1 得到负值。