A color wheel runs from 0 to 360 degrees, then starts again. CSS `mod(dividend, divisor)` handles that wraparound: it returns a division remainder with the sign of the divisor. With a positive divisor, a value that passes the end of the cycle comes back to the beginning. section 3.2.4
Find a complementary hue
A complementary hue is 180 degrees from the original. For a base hue of 225 degrees, `mod(225 + 180, 360)` becomes `mod(405, 360)`, which returns 45. Changing the base hue changes its complement without manually checking whether the result exceeds 360. section 3.2.4
Listing 3.11 Calculating a complentary color using mod()
:root {
--base-hue: 225deg; #1
--complement-hue: mod(calc(var(--base-hue) + 180deg), 360deg);
--saturation: 60%;
--lightness: 50%;
}
.original {
background-color: hsl(var(--base-hue)
var(--saturation)
var(--lightness));
}
.complement {
background-color: hsl(var(--complement-hue)
var(--saturation)
var(--lightness));
}
Use CSS custom properties to calculate `--complement-hue` with `mod()`, then pass the original and complementary hues to `hsl()` for two background colors. section 3.2.4
The same wrapping idea keeps a carousel index in range when moving backward from its first image. Be careful in JavaScript: `%` uses the dividend's sign, so `-1 % 5` is `-1`, not the wrapped index `4`. For a positive length, `((index % length) + length) % length` supplies the modulo behavior needed for the carousel. section 2.5.1 section 2.5.2
Listing 2.4 Using a true modulo to wrap an image carousel
<body>
<h1>Listing 2.4-Using a true modulo to wrap an image carousel</h1>
<img id="imageDisplay" #1
src="../images/one.png" #1
alt="Image Viewer"> #1
<br>
<button id="backButton">Back</button> #2
<button id="forwardButton">Forward</button> #2
<script>
const images = ["one.png", "two.png", "three.png",#3
"four.png", "five.png"]; #3
let currentIndex = 0;
function mod(current, length) { #4
return ((current % length) + length) % length; #4
} #4
const imageDisplay = document.getElementById("imageDisplay");
document.getElementById("backButton") #5
.addEventListener("click", function () {
currentIndex = mod(currentIndex - 1,
➥images.length); #6
imageDisplay.src = '../images/' + images[currentIndex];
}); #5
document.getElementById("forwardButton") #7
.addEventListener("click", function () {
currentIndex = mod(currentIndex + 1,
➥images.length); #8
imageDisplay.src = '../images/' + images[currentIndex];
}); #7
</script>
</body>
See the modulo utility used by Back and Forward button handlers to wrap an image-array index. section 2.5.2
