CSS: Horizontally Centering DIV of Unknown Width

The following example will show how to center a dynamic div of unknown width within another div. Since there is no dimensions you cannot center using margin: auto or text-align: center for Internet Explorer. You will have to do some css trickery to center it.

Will be centering a crude menu bar within a fixed width content box which itself will be centered in a browser window. This will work in IE 7 and 8, Firefox, Opera, Safari and Chrome.

You can see what it will look like here.

This is the html that will be used:

<div class="content">
 <div class="centerbox-outer">
        <div class="centerbox-inner">
			<a href="#">Some Link</a> |
			<a href="#">Another Link</a> |
			<a href="#">A Link</a>
        </div>
 </div>
</div>

These styles will make it work:


/*IE needs this to horizontally center the main content box in window*/
body{text-align:center}

.content {
	text-align:left;
	margin-top: 50px;

	/*center content box for all non IE browsers*/
	margin-left: auto;
	margin-right: auto;

	width:500px;
	height:300px;
	border: 1px solid #000000;
	overflow:hidden
}

/*The following is what centers the dynamic div horizontally within the content box*/
div.centerbox-outer{
    margin: 10px auto;
    float: left;
    left: 50%;
    position: relative;

}

div.centerbox-inner{
    background-color: #cccccc;
    float: left;
    position: relative;
    right: 50%;
    border: 1px solid #ffcccc;
    height: 35px;
    /*to vertically center the links*/
    line-height: 35px;
}
Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]