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.

Let’s assume you have a container div with another div inside:

<html>
	<body>
		<div id="container" style="width:100%; height:100%; background-color:red;">
			<div id="contained" style="width:50%; height:50%; background-color:green;">
				<p>I want to be centered</p>
			</div>
		</div>
	</body>
</html>

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

div not centered

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:

<html>
	<head>
		<style>
			#container {
				text-align: center;
			}
			#contained {
				text-align: left;
				display: inline-block;
			}
		</style>
	</head>
	<body>
		<div id="container" style="width:100%; height:100%; background-color:red;">
			<div id="contained" style="width:50%; height:50%; background-color:green;">
				<p>I want to be centered</p>
			</div>
		</div>
	</body>
</html>

It then looks like this:

div centered

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.

Leave a Reply

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