Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

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;
}
Hello!

Magic!

But what's going on here? If I read the Positioned Layout spec correctly, here's what's happening:

  1. 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.
  2. A defined preferred size (via width and height) can then limit an element's size inside this containing block. This result is called the used size.
  3. A defined maximum size (via max-width and max-height) can then overwrite the preferred size, again changing the used size.
  4. 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!

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 13 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles