Why doesn't min() (or max()) work with unitless 0?

后端 未结 1 398
Happy的楠姐
Happy的楠姐 2021-01-19 15:11

I\'ve searched around for an answer to this, but couldn\'t find any useful information. I\'m trying to set the top property of an element in CSS to max(0,

1条回答
  •  广开言路
    2021-01-19 15:21

    You need to add a unit to 0 otherwise it's confusing for the browser to handle the comparaison between a uniteless value and a value with unit:

    top: max(0px, 120vh - 271px)
    

    To understand this, you need to follow the specification:

    The min() or max() functions contain one or more comma-separated calculations, and represent the smallest (most negative) or largest (most positive) of them, respectively.

    Then for calculations:

    A calc() function contains a single calculation which is a sequence of values interspersed with operators, and possibly grouped by parentheses (matching the grammar),

    So basically all the rules of calc() apply to min()/max() and 0 is invalid

    Note: Because s are always interpreted as s or s, "unitless 0" s aren’t supported in calc(). That is, width: calc(0 + 5px); is invalid, even though both width: 0; and width: 5px; are valid. ref

    Related: Why doesn't css-calc() work when using 0 inside the equation?

    You may get surprised but using top:0 is valid while top:calc(0) is not. To make the latter valid it needs to be top:calc(0px). Same logic for min()/max()

    Worth to note that the same also apply to clamp() since it's equiavalent to max(MIN, min(VAL, MAX))

    0 讨论(0)
提交回复
热议问题