CSS round() Function
The round() function is a CSS math function that rounds a value to a specific interval or step.
When you build fluid layouts using percentages, viewport units (like vw), or complex calc() equations, you often end up with messy fractional values (like 33.333px). The round() function lets you clean up these numbers by snapping them to a strict interval, such as the nearest whole pixel, the nearest 50px, or the nearest 1rem.
It takes up to three arguments: an optional rounding strategy, the value you want to round, and the interval you want to round it to.
Here's an example to show it in action. When you hover over the container below, it smoothly expands from 150px to 400px. The inner blue box is set to take up 100% of that space, but we've wrapped it in round(100%, 50px). Notice how it ignores the smooth growth and snaps strictly to 50px increments.
Rounding Strategies
By default, the round() function rounds to the nearest interval. If your value is 74px and your interval is 50px, it rounds down to 50px. If your value is 76px, it rounds up to 100px.
However, you can control this behavior by passing an optional keyword as the very first argument:
nearest: (Default) Rounds to the closest interval. If the value is exactly halfway, it rounds up (towards positive infinity).up: Always rounds up to the next interval.down: Always rounds down to the previous interval.to-zero: Rounds towards zero (acts likedownfor positive numbers, andupfor negative numbers).
For example, round(up, 100%, 50px) guarantees the element will always snap to the next 50px increment.
How It Works
The value you are rounding and the rounding interval must resolve to the same type. For example, you can round a length (like vw) to another length (like px), but you cannot round a length to an <angle>.
Just like other CSS math functions, round() evaluates mathematical expressions automatically. You can write equations directly inside the arguments, such as round(var(--fluid-width) * 2, 10px).
Official Syntax
The official syntax of the round() function is as follows:
Where <rounding-strategy> is defined as:
Possible Values
As indicated in the official syntax, the round() function accepts the following values:
- rounding-strategy
An optional keyword (
nearest,up,down, orto-zero) that dictates how the rounding is calculated. If omitted, it defaults tonearest.- calc-sum (Value to Round)
The dynamic value or calculation that you want to round.
- calc-sum (Rounding Interval)
The step or interval you want to snap the value to (e.g.,
50px,1rem, or5%).
CSS Specifications
- The
round()function is defined in CSS Values and Units Module Level 4 (Editor's Draft)
Browser Support
The following table provided by Caniuse.com shows the level of browser support for this feature.