Rounding, remainder and comparison
Definition and purpose
Stepped math functions help align lengths to a grid and compute repeating offsets. round() returns a multiple of an interval. mod() and rem() both compute remainders but differ when signs disagree.
Quantized width
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #a { width: round(up, 53px, 8px); } #b { width: round(down, 53px, 8px); } </style> </head> <body> <div id="a">Panel</div> <div id="b">Other</div> </body></html>The upper and lower grid steps bracket the input.
Syntax and mental model
round(nearest, 53px, 8px) gives 56px; up rounds toward positive infinity, down toward negative infinity and to-zero toward zero. Ties in nearest favor positive infinity. With a positive divisor, mod(-18px, 5px) gives 2px, while rem(-18px, 5px) gives -3px. abs() returns magnitude and sign() returns the dimensionless sign. Use compatible types and nonzero intervals.
Negative remainder
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } #a { position: relative; left: mod(-18px, 5px); } #b { position: relative; left: rem(-18px, 5px); } </style> </head> <body> <div id="a">Panel</div> <div id="b">Other</div> </body></html>Modulo follows divisor sign; remainder follows dividend sign.
Common mistakes
Rounding down is not truncation for negatives. Avoid testing a negative width to distinguish remainder signs, because width range-clamping can hide the difference; use a signed inset instead.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Trigonometric and exponential functions. Next lesson: Functional values and environment.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Rounding, remainder and comparison — knowledge check
Five questions on rounding, remainder and comparison.
What is round(down, -13px, 10px)?
What is round(to-zero, -13px, 10px)?
What is mod(-13px, 10px)?
What is rem(-13px, 10px)?
What is abs(-12px)?