Manuel Matuzovic: max() Trickery
Publikováno: 18.10.2022
By way of a post by Manuel Matuzović which is by way of a demo by Temani Afif.
.wrapper {
margin-inline: max(0px, ((100% - 64rem) / 2));
}
You’d be doing yourself a favor to read Manuel’s breakdown of …
Manuel Matuzovic: max() Trickery originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
By way of a post by Manuel Matuzović which is by way of a demo by Temani Afif.
.wrapper {
margin-inline: max(0px, ((100% - 64rem) / 2));
}
You’d be doing yourself a favor to read Manuel’s breakdown of all what’s happening here, but it basically works out to the equivalent of this longer syntax:
.wrapper {
max-width: 64rem;
margin: 0 auto;
width: 100%;
}
…where:
- max() acecepts a comma-separated list of CSS numeric values, where the applied value is the largest (or as MDN puts it, the “most positive”) one in the set.
0px
is the first value in the set, ensuring that the smallest value is always going to be greater than zero pixels.(100% - 64rem)
is the second “value” in the set, but is expressed as a calculation (note thatcalc()
is unnecessary) that subracts the themax-width
of the element (64rem
) from its full availablewidth
(100%
). What’s left is the space not taken up by the element.((100% - 64rem) / 2))
divides that remaining space equally since we’re divying it between the inline boundaries of the element.max(0px, ((100% - 64rem) / 2))
compares0px
and(100% - 64rem) / 2)
. The largest value is used. That’ll be the result of the equation in most cases, but if64rem
is ever greater than the computed value of the element’s full100%
width, it’ll lock that value at zero to ensure it never results in a negative value.margin-inline
is the property that the winning value sets, which applies margin to the inline sides of the element — that’s the logical shorthand equivalent to setting the same value to themargin-left
andmargin-right
physical properties.
It’s the same sort of idea Chris shared a while back that uses the CSS max()
function to solve the “Inside Problem” — a container that supports a full-bleed background color while constraining the content inside it with padding
.
max()
, calc()
, margin-inline
… that’s a lot of newfangled CSS! And Manuel is right smack dab in the middle of writing about these and other modern CSS features over 100 days.
To Shared Link — Permalink on CSS-Tricks
Manuel Matuzovic: max() Trickery originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.