Use rem() when an alternating layout must keep its direction on both sides of a center line. The CSS function rem(dividend, divisor) returns the remainder after division. Unlike mod(), its result takes the sign of the dividend, matching JavaScript’s % remainder operator. A negative dividend therefore produces a negative remainder; a positive dividend produces a positive one. section 3.2.4
That sign preservation is useful for offsets rather than cycles. In a timeline, values below zero can move items left, values above zero can move them right, and a zero remainder leaves an item unshifted. Dividing an index by 2 makes every other value contribute a signed remainder, so the same calculation both alternates placement and retains which side of the center an item belongs on. section 3.2.4
Alternate a timeline offset
Store an index in a custom property and multiply its remainder by an offset distance: .item { transform: translateX(calc(rem(var(--index), 2) * 30px)); } Here rem(var(--index), 2) supplies the direction and the 30px value supplies the visible distance. Generate positive and negative --index values to make successive events zigzag outward. section 3.2.4
Listing 3.13 Generating alternating index values
const timeline = document.getElementById('timeline');
let offsetDirection = -1; #1
const events = [ #2
'Launched MVP',
'Reached 1,000 users',
'Raised seed round',
'Hired first engineer',
'Redesigned homepage',
'Expanded internationally',
];
events.forEach((text, i) => { #3
const item = document.createElement('div'); #4
item.classList.add('item'); #4
item.textContent = text; #4
if(i % 2 !== 0) { offsetDirection *= -1; } #5
item.style.setProperty('--index', #6
(i + 1) * offsetDirection); #7
timeline.appendChild(item);
});
This JavaScript builds timeline items and assigns alternating signed --index values before CSS uses rem() to position them. section 3.2.4
Choose rem() when the dividend’s sign carries meaning. Choose mod() when values should wrap consistently according to the divisor’s sign, such as cyclic color-wheel or carousel behavior. For responsive CSS math, rem() can sit inside calc() and work with custom properties like the timeline index. section 3.2.4 section 3.7
