Fit height to background pattern size with calc-size
How to round a section height to the background pattern with calc-size() and round().
Hey everyone,
I published a new article on an interesting use case for calc-size() and round() in CSS. I mentioned it briefly in a previous newsletter, and now I wrote an article on it.
Fit height to background pattern size with calc-size()
When a section has a background pattern, we sometimes want the pattern to fit the container's height exactly, so there are no cut-off tiles at the bottom.
Take a look at the following figure:

Notice how the pattern above the pink line is cut off. How can we avoid that? The article shows how to round the container's height up to the nearest multiple of the pattern's tile height.
Here is the result:

Take a look at the final CSS, but I highly recommend reading the article. It's short and straightforward.
.section {
/* This must match the size of the pattern image. */
--tile-width: 52px;
--tile-height: 44px;
background-image: url("pattern.svg");
background-size: var(--tile-width) var(--tile-height);
padding-block: round(up, 1rem, var(--tile-height));
height: calc-size(auto, round(up, size, var(--tile-height)));
}
What do you think of the solution? Have you come across interesting CSS solutions like this one?
Keep learning
If you enjoyed this, you might like The Layout Maestro, my interactive CSS layout course. I built it to help you understand layout and know which method to use, and when.
Check out The Layout Maestro and enroll for $189. Use the code oct26 to get $10 off.
Thanks for reading.
Ahmad
Add a comment: