Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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, 120vh - 271px). I've tried several variations of this:

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

Is there something wrong with my syntax? I keep getting Chrome telling me that this is an invalid property error.

Invalid property error as shown in Chrome

In practice, I'm actually using CSS variables for the numbers. so 120vh is actually var(--height) or something like that. When I use CSS variables, the line just doesn't do anything. It doesn't apply the style, and I don't get any warnings. What am I doing wrong here?

I'm using the newest version of Chrome (83 I believe), so this should be supported.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
519 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 <calc-sum> grammar),

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

Note: Because <number-token>s are always interpreted as <number>s or <integer>s, "unitless 0" <length>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))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...