Css absolute position won't work with margin-left: auto and margin-right: auto
Horizontally centering an absolutely positioned element requires a combination of left: 0
, right: 0
, and margin: auto
. Additionally, the element must have a declared width
. This is because margin-left: auto
and margin-right: auto
are unresponsive with absolute positioning since it removes the element from the normal document flow.
Additionally, ensure you set a fixed height and width to your absolutely positioned element, alongside top: 0;
, bottom: 0;
, and margin: auto;
to achieve both horizontal and vertical centering.
Inside the mechanics of positioning and margins
Get in-depth with the behaviors and interaction between different positioning values and margin configurations.
Horizontal centering alone
If you're looking to center your element horizontally only, top
and bottom
properties won't be required:
Vertical centering
To center your element vertically, replace left
and right
properties with top
and bottom
respectively:
Rotate the transform way: Horizontal centering
Here's a stylish way of horizontally centering while considering element scaling–the magic word is transform
:
Note that transform
adjusts only the visual representation, not the layout size.
When margins alone fail
Auto margins can work wonders–but only within the normal document flow. When an element is absolutely positioned, it's yanked from this flow, making margins insufficient for centering.
Witness the magic: Practical demonstration
Grasping a visual concept can be a game changer. Use this JSFiddle link [http://jsfiddle.net/38tjjdpd/16/] to witness different techniques for centering with absolute positioning.
Going under the hood of absolute positioning
While wielding absolute positioning, elements sit relative to their closest positioned ancestor. In the absence of positioned ancestors, they take root to the viewport.
Between Relative and Absolute
The plot twist? margin: 0 auto;
works like a charm when an element's position
is set to relative
. This is because relatively positioned elements stay within the normal document flow.
Looking out: Possible complications
Usage of absolute positioning comes with a caution note: Overlapping elements. This comes into picture especially when you shun fixed dimensions, or the viewport size gets tweaked.
Was this article helpful?