'link <a> has 100% width in display flex, <button> don't

I want my button to be aligned to the right, no matter the container (so no flex parent). So i want to use a margin-left: auto to push the button to the right. I'm aware of other solutions (float, flex,...) but want to know why this behaviour append.

Here is my problem :
This work on < button > but not with < a > tag.
The < a > seems scale to 100% width.

Here is a sample that illustrate the problem :

a, button {
  display: flex;
  margin-left: auto;
}
<a href="">test</a>
<br>
<button>test</button>

I searched for hidden user agent properties but could'nt find anything.

Is this a native behaviour from < a >, or maybe a margin-left: auto weird behaviour ? If someone has an idea ?

Same with bootstrap utility :

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="ms-auto w-25">This is working</div>

<a class="ms-auto w-25">This is not working</a>

Why is this not working on < a > tags ?



Solution 1:[1]

buttons are a bit special and won't behave the same as a link. Instead of flex, you can use table to get the same behavior

a, button {
  display: table;
  margin-left: auto;
}
<a href="">test</a>
<br>
<button>test</button>

Solution 2:[2]

Because button is a block-level element and a is anchor inline element that's why margin-left: auto; not working on the anchor tag.

You can try:

a, button {
  display: flex;
  margin-left: auto;
  justify-content:flex-end;
}
<a href="">test</a>
<br>
<button>test</button>

Solution 3:[3]

In ordered to have margin auto work you need also to specify a width, So to push it on the right with the use of margin auto you have to use this :

button, a {
    display: flex;
    margin: 0 0 0 auto;
    width: 50px;
}
<a href="">test</a>
<br>
<button>test</button>

Also instead of flex i'd recommand you would use display: block; or inline-block if you don't want it full width. If you're not going to use flexbox i don't see the need to include it.

The flex version of it would be much easier and clean though, you can do it this way :

button, a {
    display: flex;
  justify-content: flex-end;
  margin: 0 0 0 auto;
}
<a href="">test</a>
<br>
<button>test</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Temani Afif
Solution 2 Yash porwal
Solution 3