CSS: Center variable width divs horizontally

When centering divs, if your div has a fixed width you can either absolutely position it and set negative margins as shown in this post. Another way to center such a fixed width div horizontally is to set both its left and right margin to auto. The browser then has to set both margins to the same value.

Unfortunately known of these two techniques can be used if your div doesn’t have a fixed width. In this case, you’ll need a different solution.

The container div will fill the whole window while the contained div will fill the upper left corner:

The trick is to set a centered text alignment on the container and set an inline-block display on the contained div. Of course the text-align CSS property will be inherited by the contained div so you’ll need to set it back to left:

I actually found it while changing all possible properties on the container and contained div. Just by chance. It still doesn’t make much sense to me but it does work. Before figuring this out, I was always using some JavaScript to find out the actual width of the contained div and set the margins accordingly and recomputing it on any resize. In case you are still interested in a jQuery solution, please check Manos Malihutsakis Blog.

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners.OkRead more