Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Anchor tag stretching while Button tag is not when applying the same exact class with flex

My desired outcome is that neither of my buttons should stretch and they should instead both only take up the space of the content inside them without needing to explicitly set a width.

I fail to understand why there would be a difference between the button and the link when they both have display: flex. Is there some default CSS I am not aware of?

.my-button {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #515151;
    color: white;
    width: auto;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 0.25rem;
    font-size: 0.875rem;
    font-family: sans-serif;
    text-decoration: none;
    cursor: pointer;
}
<button class="my-button" type="button">Button (button)</button>

<br>

<a href="" class="my-button">Button (link)</a>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As mentioneed here, display: flex; doesn’t work on buttons, so technically the a tag is the one that’s behaving properly, where the button tag is not.

Here you can find a bug report about this.

You can fix this with using a button group and display: block;:

.btn-group button {
    display: block;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #515151;
    color: white;
    width: auto;
    padding: 0.5rem 1rem;
    margin-bottom: 10px;
    border: none;
    width: 150px;
    border-radius: 0.25rem;
    font-size: 0.875rem;
    font-family: sans-serif;
    text-decoration: none;
    cursor: pointer;
}

.btn-group button:not(:last-child) {
  border-bottom: none; /* Prevent double borders */
}

/* Add a background color on hover */
.btn-group button:hover {
  background-color: #3e8e41;
}
<div class="btn-group">
  <button>Button (button)</button>
  <button>Button (link)</button>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading