How to center absolute div horizontally using CSS?

You need to set left: 0 and right: 0.

This specifies how far to offset the margin edges from the sides of the window.

Like ‘top’, but specifies how far a box’s right margin edge is offset to the [left/right] of the [right/left] edge of the box’s containing block.

Source:
http://www.w3.org/TR/CSS2/visuren.html#position-props

Note: The element must have a width smaller than the window or else it will take up the entire width of the window.

You could use media queries to specify a minimum margin, and then transition to auto for larger screen sizes.


.container {
  left:0;
  right:0;

  margin-left: auto;
  margin-right: auto;

  position: absolute;
  width: 40%;

  outline: 1px solid black;
  background: white;
}
<div class="container">
  Donec ullamcorper nulla non metus auctor fringilla.
  Maecenas faucibus mollis interdum.
  Sed posuere consectetur est at lobortis.
  Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
  Sed posuere consectetur est at lobortis.
</div>

Leave a Comment