This example demonstrates how the round()
function's rounding strategies work for positive values.
Of the five boxes below, the round()
function is used to set the height of the last four. The value to be rounded is between 100 px and 125 px in each case, and the rounding value is 25px in all cases. The height of the boxes is therefore either rounded up to 125 px or down to 100 px.
HTML
The HTML defines 5 div
elements that will be rendered as boxes by the CSS. The elements contain text indicating the rounding strategy, initial value, and expected final height of the box (in brackets).
<div class="box box-1">height: 100px</div>
<div class="box box-2">up 101px (125px)</div>
<div class="box box-3">down 122px (100px)</div>
<div class="box box-4">to-zero 120px (100px)</div>
<div class="box box-5">nearest 117px (125px)</div>
CSS
The CSS that is applied to all boxes is shown below. Note that we apply a custom CSS property named --rounding-interval
, that we will use for the rounding interval.
div.box {
width: 100px;
height: 100px;
background: lightblue;
padding: 5px;
--rounding-interval: 25px;
}
The first div
from the left isn't targeted with specific CSS rules, so it will have a default height of 100px. The CSS for div
two, three, and four is shown below, which round, up, down, and to-zero, respectively.
div.box-2 {
height: round(up, 101px, var(--rounding-interval));
}
div.box-3 {
height: round(down, 122px, var(--rounding-interval));
}
div.box-4 {
height: round(to-zero, 120px, var(--rounding-interval));
}
Notice how above we indicate the rounding interval using var()
and the custom CSS property --rounding-interval
.
The last box is set without specifying a rounding strategy, and hence defaults to nearest
. In this case, the nearest interval to 117 px is 125px, so it will round up. Just for contrast, here we specified hard coded values for both the rounding value and interval. While this is allowed, you wouldn't do this normally because there is no point rounding a number when you already know what the result must be.
div.box-5 {
height: round(117px, 25px);
}
Result
If the browser supports the CSS round()
function, you should see five columns with heights that are rounded as indicated by their contained text.