Million Miles Technologies

The CSS stepped value math functions are now in Baseline 2024  |  Blog  |  web.dev


Rachel Andrew

All major engines now support the CSS stepped value math functions—
round(),
mod(),
and rem().

The stepped value functions all transform a given value according to another
step value.

The round() function

The round() function takes a value to be rounded,
a rounding interval, and an optional rounding strategy.
The value is rounded according to the rounding strategy,
to the nearest integer multiple of the rounding interval.

Either the value to be rounded, or the rounded interval, should be a CSS
custom property. While it’s valid to hardcode both values, there’s little
point rounding a number if you could calculate the value yourself.

The following CSS rounds the value of --my-font-size, to the interval of 1rem.

font-size: round(var(--my-font-size), 1rem);

The default rounding strategy is nearest. The previous example including the
rounding strategy is as follows:

font-size: round(nearest,var(--my-font-size), 1rem);

The possible values for the rounding strategy are:

  • up: Equivalent to JavaScript Math.ceil() method. Rounds the value up
    to the nearest whole multiple of the rounding interval.
  • down: Equivalent to JavaScript Math.floor() method. Rounds the value
    down to the nearest whole multiple of the rounding interval.
  • nearest (default): Equivalent to JavaScript Math.round(). Rounds the
    value up or down, to the nearest whole multiple of the rounding interval.
  • to-zero: Equivalent to JavaScript Math.trunc() method. Rounds the value
    to the nearest integer multiple of the rounding interval closer to zero.

Learn more about round() in
The New CSS Math: round(),
by Dan Wilson.

The rem() and mod() functions

The rem() and mod() CSS functions work in a similar way to the JavaScript
remainder operator (%). They take two values, the first (the dividend) is divided by the second (the divisor),
and the remainder is returned.

margin: rem(18px, 5px); /* returns 3px */

The difference between the two functions is that rem() always takes the sign
of the dividend, therefore if the first value is positive the returned value
will be positive. The mod() function takes the sign of the divisor.

Learn more about rem() and mod() in
The New CSS Math: rem() and mod(),
by Dan Wilson.

Related blogs