How to fix absolute position won’t work with margin-left: auto margin-right: auto with CSS?

Spread the love

To fix absolute position won’t work with margin-left: auto margin-right: auto with CSS, we set the element’s width and height.

For instance, we write

div {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 200px;
  height: 200px;
}

to set the width and height of the div to 200px.

And then margin: auto will center the div even if it has absolute position.

Leave a Reply

Your email address will not be published. Required fields are marked *