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! 😋

47 thoughts on “Center a div with unknown width – CSS trick”

  1. One more thing. I do believe that there are several travel insurance web pages of dependable companies than enable you to enter a trip details and obtain you the insurance quotes. You can also purchase the particular international travel cover policy on-line by using the credit card. All you should do should be to enter your current travel details and you can understand the plans side-by-side. Only find the system that suits your financial budget and needs and use your credit card to buy the item. Travel insurance online is a good way to start looking for a reliable company to get international holiday insurance. Thanks for revealing your ideas.

  2. Thank you, I’ve just been searching for information about this subject for a long time and yours is the best I have came upon till now. However, what about the bottom line? Are you positive about the supply?

  3. An interesting dialogue is value comment. I feel that it is best to write extra on this topic, it may not be a taboo topic however usually persons are not enough to talk on such topics. To the next. Cheers

  4. Excellent submit.. video youtube terfavorit I used to be reviewing continuously this website and I am influenced! Very useful details particularly the shutting down element 🙂 I contend with such information lots. I was in search of this type of data for a quite a while. Appreciate it and also connected with good luck.

Leave a Reply

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