CSS mod() Function
The mod() function is a CSS math function that returns the modulus, or remainder, of a division operation.
If you divide 10 by 3, the answer is 3 with a remainder of 1. The mod() function performs this exact calculation and returns that leftover remainder (in this case, 1). You provide it with two arguments: the dividend (the number being divided) and the divisor (the number you are dividing by).
This function is highly practical for creating cyclic patterns, alternating layouts, or keeping a value within a specific range. For example, if you want an angle to always stay between 0 and 360 degrees, you could use mod(var(--angle), 360deg).
Here's an example where we use mod() to create a repeating "staircase" layout. We assign a simple index number (0 through 5) to a series of boxes. By calculating mod(var(--i), 3), the remainder cycles through 0, 1, 2, and then resets back to 0, 1, 2. We then multiply that remainder by 40px to create our repeating indentation:
The Difference Between mod() and rem()
CSS actually has two functions for finding remainders: mod() and rem(). They behave identically when dealing with positive numbers, but they handle negative numbers differently.
The difference lies in which sign the final result takes:
- The
mod()function always takes the sign of the divisor (the second argument). - The
rem()function always takes the sign of the dividend (the first argument).
For example, mod(-10, 3) returns 2 (positive, matching the 3), while rem(-10, 3) returns -1 (negative, matching the -10).
How It Works
The mod() function accepts two calculations. These arguments must either be the same type (like two lengths or two angles), or one of them must be a unitless number.
Just like the calc() function, mod() evaluates mathematical expressions automatically. You can write equations directly inside the arguments, such as mod(var(--width) + 20px, 100px).
Official Syntax
The official syntax of the mod() function is as follows:
Possible Values
As indicated in the official syntax, the mod() function accepts two values:
- calc-sum (Dividend)
The value that is being divided.
- calc-sum (Divisor)
The value you are dividing by. The function will return the remainder of this division, and the result will share the same positive or negative sign as this divisor.
CSS Specifications
- The
mod()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.