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.
It’s clever, sure, but I think the longer version is much easier to understand, which is a very important advantage.
Also, would
margin-inline: auto;
be a better equivalent thanmargin: 0 auto;
because the one-line version leaves the block margins unspecified.Always gotta lean toward what is most understandable to you!
I imagine we’d only need to declare
0
on the block-direction margin there’s margin coming in from somewhere else that needs to be overidden.Clever but the longer form is easier to override with media queries or higher specificity. Eg you may just have to override the max-width rather than the entire line, which is easier to read in the override.
Agreed that the longer version is easier to understand for other levels of devs and easier to override. Not really worth it.