Center Align on a Absolutely Positioned Div
For absolute centering of a div, set its position to absolute and adjust its own dimensions with transform. Like this:
Now, use it in your HTML:
The top
and left
at 50% bring the top-left corner towards the center, while transform
translates the div back by half of its width and height — aligning it dead center!
When dimensions aren't set
When the dimensions of the div are known, the technique above works perfectly. For variable dimensions, we have another move—the transform
property:
Pro-tip: Make sure the parent has positioning (relative
, absolute
, or fixed
) to set the containing block for the absolutely positioned element.
Dealing with troublesome cases
Juggling fluid content can be tricky. Without set sizes, the transform method is your comrade, adjusting to the changing dimensions automatically. But, when the width is fixed, there's a nifty alternative:
And remember, the z-index property is your friend to make sure your elements don't have overlapping personal space.
Horizontal versus vertical
For the horizontally inclined:
Want to center a fixed-width div? Set left
and right
to 0 and let the margin do the rest:
For fluid-width divs, where width
cannot be determined beforehand, you guessed it, transform
is the way to go:
For those wanting to go vertical:
Vertically centering is as easy as using top and transform:
Accessible centering
Don't forget screen readers. Use semantic HTML to ensure your aligned content is also accessible to all users.
Embrace the quirks
One browser's center might be another browser's lopsided nightmare. Regularly cross-test your alignment across browsers, and employ tools like Autoprefixer to deal with vendor prefixes.
Treading on the shoulders of giants
Words of wisdom: It's okay to leverage proven patterns. Wonderful folks at CSS-Tricks, Smashing Magazine, and MDN Web Docs hold valuable wisdom on centering techniques, so don't shy away from learning from them!
Was this article helpful?