Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

css-calc

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.

like image 583
Jaden Baptista Avatar asked Jun 22 '20 18:06

Jaden Baptista


Video Answer


1 Answers

You need to add a unit to 0 otherwise it's confusing for the browser to handle the comparison between a uniteless value (a <number>) and a value with unit (a <length>) and the top property accept a <length> not a <number>

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 the content of min()/max() is treated like the one of calc() then from the type checking

A math function can be many possible types, such as <length>, <number>, etc., depending on the calculations it contains, as defined below. It can be used anywhere a value of that type is allowed.

and

Note: Altho there are a few properties in which a bare <number> becomes a <length> at used-value time (specifically, line-height and tab-size), <number>s never become "length-like" in calc(). They always stay as <number>s.

You may get surprised but using top:0 is valid while top:min(0) or top:max(0) is not. To make them valid you need to add the unit.

But you can use opacity: min(0) for example since opacity accept a number as argument.

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

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

like image 66
Temani Afif Avatar answered Nov 15 '22 08:11

Temani Afif