AndrewMk
AndrewMk

Reputation: 703

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>

Upvotes: 0

Views: 127

Answers (2)

heyitsjhu
heyitsjhu

Reputation: 981

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/

Upvotes: 1

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

You may give text-align:center to parent div if any.

To use margin-auto we need to specify width of the div. auto will take 100% width for div and p tags.

If you can find out and give specific width for div so that, else based on your browser suppport you use property width:max-content; , read about it here

You may use browser hack for this as:

width: intrinsic;           /* Safari/WebKit uses a non-standard name */
width: -moz-max-content;    /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */

Example snippet:

<div style="background:red;margin:auto;width:intrinsic;width:-moz-max-content;width:-webkit-max-content;">
  <a href="#">Dummy link</a>
</div>

Upvotes: 0

Related Questions