AndrewMk AndrewMk - 2 months ago 6
CSS Question

width auto does not get centered

Why does elements with auto width defined does not get centered when I try to assign the margin (left and right) auto for it?. Is there any trick other than the margins to center elements with auto width?

Here is the code:

<div style="width:auto; margin:0 auto 50px;">
<a href="#">Dummy link</a>
</div>

Answer

Add display: inline-block to, and remove width:auto from, your current <div>. Then, create an outer <div>, if you don't have one already, and add text-align: center to it.

<div style="text-align:center;"> <div style="display:inline-block; margin:0 auto 50px;"> <a href="#">Dummy link</a> </div> </div>

JSFiddle: https://jsfiddle.net/uLp7qj3e/