Skip to content

[css-values] Add sign() math function #4673

@Loirooriol

Description

@Loirooriol

Can we add the analogous of the ECMAScript Math.sign()? That is

  • sign(x) is 1 if x > +0
  • sign(+0) is +0
  • sign(-0) is -0
  • sign(x) is -1 if x < -0
  • sign(NaN) is NaN

For non-zero values it can be achieved with x / hypot(x) or clamp(-1, x / 0, 1), but these are NaN for zero.

I think sign() can be very useful given that CSS doesn't have conditionals (#3455).

For example:

width: calc(if (100vw > 100px) then (1em) else (1lh));

is not possible, but with sign() I could use

--cond: sign(max((100vw - 100px) / 1px, 0));
width: calc(1em * var(--cond) + 1lh * (1 - var(--cond)));

Or #2513 is discussing a round() function that rounds to the nearest, or upwards in case of tie. So round(2.5) would be 3 and round(-2.5) would be -2. But what if in case of tie I want to round towards 0, or away from zero? It's very simple with sign():

round(-hypot(x)) * sign(-x) /* round towards 0 in case of tie */
round(hypot(x)) * sign(x) /* round away from 0 in case of tie */

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions