Best ways to center align div with CSS
Center align division with CSS
Solution #1 - margin 0 auto
This is an often-used and widely supported method and clean. However the drawback is you have to specify the width of the item. This reduce the flexibility and can be used only in limited scenarios.
margin:0 auto; width:80%;
Solution #2 - left -50%, left 50%
This solution fixes the limitation where you have to specify the width of the content. With the code below, the container would be class="menu" and your content would be the <ul></ul> which could have any content and would always be center-aligned !
div#menu-primary .menu { float: right; left: -50%; position: relative; } div#menu-primary .menu ul { left: 50%; list-style: none outside none; position: relative; }
Test:
- Item 1
- Item 2
- Item 3
Solution #3 - Traditional center alignment
<center> <div align="center"></div> </center>
Test !
This is not proper modern code, but is supported by all and the most older (ancient) browser - hence makes it the most widely supported solution.
Solution #4 - Use inline-block inside display:table div
variable width div.. for example english/french text of different width
Solution #5 - Use inline-block inside a text-align:center element
This is not supported by IE6, 7 or 8.
Test fails in IE6, IE7 and IE8
Recent Comments