5.6 · Logic in CSS

Math in CSS: round(), mod() and sin()

Snap values, repeat patterns and lay things out on a circle with built-in math.

round(value, step) snaps to the nearest step, and up, down or to-zero pick the direction. mod() and rem() return what’s left after division, which makes repeating patterns. abs(), sign(), pow() and sqrt() are there too.

Trigonometry works with real angles: sin(), cos(), tan() and their inverses. Placing items on a circle becomes two calc()s.

Before
// Positions computed in JS
items.forEach((item, i) => {
  const a = (i / items.length) * Math.PI * 2
  item.style.left = Math.cos(a) * r + 'px'
  item.style.top = Math.sin(a) * r + 'px'
})
Now
span {
  translate:
    calc(cos(var(--i) * 30deg) * 6rem)
    calc(sin(var(--i) * 30deg) * 6rem);
  background: oklch(78% 0.13
    calc(mod(var(--i), 3) * 120));
}
.bar { inline-size: round(var(--w), 10%); }