- Revealed at
- Up to date at
- Studying time
- 2min
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:
- 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. - A outlined most popular measurement (through
width
andtop
) can then restrict a component’s measurement inside this containing block. This end result known as the used measurement. - A outlined most measurement (through
max-width
andmax-height
) can then overwrite the popular measurement, once more altering the used measurement. - 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!
Sure? Cool! You may need to try Internet Weekly for extra fast learnings. The final version went out 11 days in the past.