The basic technique for a horizontal centering of an element with a fixed width is:
margin-left: auto; margin-right: auto;
In some cases it can be shortened to:
margin: 0 auto;
Complete example:
<style> .center { width: 780px; margin: 0 auto; } </style> <div class="container"> <div class="center">...</div> </div>
Width can be set with width
or max-width
.
If width of element is unknown we change element to:
display: inline-block;
and use on parent:
text-align: center;
I additionally reverted text alignment in the child and limit a width of a centered element, complete example:
<style> .container { text-align: center; } .center { display: inline-block; text-align: left; max-width: 480px; } </style> <div class="container"> <div class="center">...</div> </div>
A bit complicated solution is using a float with 50% offset. Working example:
<style> .container { overflow: hidden; } .helper { position: relative; float: left; left: 50%; } .center { position: relative; left: -50%; max-width: 480px; } </style> <div class="container"> <div class="helper"> <div class="center">...</div> </div> </div>
Centered content was moved back by a half of its width and its center became left edge of wrapping
float which itself was moved to the center of a container. position: relative
makes possible to
specify left
offset.
http://stackoverflow.com/questions/283961/centering-a-div-block-without-the-width http://stackoverflow.com/questions/18524722/center-an-auto-width-div