Auto-margin works with absolute positioned elements
- Published at
- Updated at
- Reading time
- 2min
How often do you set margin
on absolute positioned elements? I rarely do it and might even say I've never done it. I mean, the whole point of absolute positioning is to place an element in its container. What's there to margin?
But while reading Josh Comeau's guide on div centering, I learned a CSS trick that I will remember.
Let's say you want to center a modal — how do you do it?
For years, I moved the element to the middle and then moved it back by its half width and height. Et voilà!
.box {
position: absolute;
top: 50%;
left: 50%;
translate: -50% -50%;
}
While this approach works, it always felt clunky. An alternative is not to rely on absolute positioning with flexbox or grid. And that's fair, but what if we still want to center with position: absolute
?
Josh taught me a nifty magic trick. Check this out. 👇
.box {
position: absolute;
inset: 0.5rem;
}
Magic!
But what's going on here? If I read the Positioned Layout spec correctly, here's what's happening:
- The size of an absolute positioned element is calculated via its "inset" properties (
top
,left
,inset
, ...). The resulting box is then called inset-modified containing block. - A defined preferred size (via
width
andheight
) can then limit an element's size inside this containing block. This result is called the used size. - A defined maximum size (via
max-width
andmax-height
) can then overwrite the preferred size, again changing the used size. - And here's the catch: if we now have a containing block defined via inset properties, but the element's used size is not filling it out. Then
margin: auto
comes into play and distributes the available space on each axis.
Holy moly!
Thanks, Josh; I'll add this trick to my toolbox!
Join 5.5k readers and learn something new every week with Web Weekly.