skip to Main Content

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>

2

Answers


  1. 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>
    Login or Signup to reply.
  2. Set the width to min-content.

    Optionally, apply white-space: nowrap so the text does not break.

    .my-button {
      background-color: #515151;
      color: white;
      width: min-content;
      padding: 0.5rem 1rem;
      border: none;
      border-radius: 0.25rem;
      font-size: 0.875rem;
      font-family: sans-serif;
      text-decoration: none;
      cursor: pointer;
      /*     white-space:nowrap; optional */
      margin-bottom: 1em;
    }
    <button class="my-button" type="button">Button (button)</button>
    
    <br>
    
    <a href="" class="my-button">Button (link)</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search