Posted almost 8 years ago. Visible to the public.

How to horizontally center absolute positioned container with CSS

Note: We have card with all CSS centering options. You probably want to head over there and get an overview over what techniques are available for your use case and browser requirements.


Horizontally centering a static element in CSS is normally handled by setting the left and right margins to auto, for example:

Copy
// SASS $container_width: 100px .container width: $container_width margin: 0 auto

However, this won’t work on an absolutely positioned element. But there is a solution:

Copy
// SASS $container_width: 100px .container width: $container_width position: absolute left: 50% margin-left: floor($container_width / 2) * -1

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Martin Straub
Last edit:
about 5 years ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Martin Straub to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more