Center a div with unknown width – CSS trick

To center a div, the typical  margin: 0 auto;  css attribute requires a known width for it to work, either a percentage or a fixed number of pixels. I came across this StackOverflow answer the other day that solves this perfectly. Sadly it’s not even the accepted answer 😕

#wrapper {
   position: relative;
   left: 50%;
   float: left;
}
#page {
   position: relative;
   left: -50%;
   float: left;
}

Note that in css, position: relative;  means relative to the block’s “normal” position, so it’s an offset to its original position.

Percentage values for left are interpreted as the percentages of the parent width. In this case, page div should be wrapper‘s only child, so their widths would be the same, hence the left: -50% for page moves the block to the left by half of the width of itself, along with the 50% offset of its parent, it’s centered! 😋

Leave a Reply

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