Search code examples
htmlcss

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>


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>