Saturday, April 27, 2024
HomeJavaScriptAuto-margin works with absolute positioned components

Auto-margin works with absolute positioned components


Revealed at

Up to date at

Studying time
2min

This submit is a part of my Right now I discovered sequence through which I share all my net improvement learnings.

How typically do you set margin on absolute positioned components? I not often do it and may even say I’ve by no means achieved it. I imply, the entire level of absolute positioning is to put a component in its container. What’s there to margin?

However whereas studying Josh Comeau’s information on div centering, I discovered a CSS trick that I’ll bear in mind.

For instance you need to middle a modal — how do you do it?

For years, I moved the ingredient to the center after which moved it again by its half width and top. Et voilà!

.field {
  place: absolute;
  prime: 50%;
  left: 50%;
  translate: -50% -50%;
}

Whereas this strategy works, it all the time felt clunky. Another is to not depend on absolute positioning with flexbox or grid. And that is truthful, however what if we nonetheless need to middle with place: absolute?

Josh taught me a nifty magic trick. Test this out. 👇

Magic!

However what is going on on right here? If I learn the Positioned Format spec appropriately, here is what’s occurring:

  1. The scale of an absolute positioned ingredient is calculated through its “inset” properties (prime, left, inset, …). The ensuing field is then known as inset-modified containing block.
  2. A outlined most popular measurement (through width and top) can then restrict a component’s measurement inside this containing block. This end result known as the used measurement.
  3. A outlined most measurement (through max-width and max-height) can then overwrite the popular measurement, once more altering the used measurement.
  4. And here is the catch: if we now have a containing block outlined through inset properties, however the ingredient’s used measurement just isn’t filling it out. Then margin: auto comes into play and distributes the out there house on every axis.

Holy moly!

Thanks, Josh; I am going to add this trick to my toolbox!

Was this TIL submit useful?
Sure? Cool! You may need to try Internet Weekly for extra fast learnings. The final version went out 11 days in the past.
Stefan standing in the park in front of a green background

Associated Matters

Associated Articles

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments