htmlcsstwitter-bootstrapflexboxwidth

How to make a flexbox container auto-width and centered with buttons aligned next to each other?


Im using the following code, but the container is still full width

I'd like it to adapt to the width of its contents

.cta-primary {
    display: flex;
    justify-content: center;
    align-items: center;
    width: auto; /* Container width is determined by its contents */
    margin: 0 auto; /* Centers the container within its parent */
}

.cta-primary .button-group {
    display: flex;
    gap: 10px; /* Optional spacing between buttons */
}
<div class="cta-primary">
    <div class="button-group">
        <a href="contact" class="btn btn-primary">One</a>
        <a href="contact" class="btn btn-primary">Two</a>
    </div>
</div>

I tried width: auto but it makes no difference


Solution

  • You have to make it inline-flex and then center it using any appropriate method on it's parent.

    body {
      text-align: center;
    }
    
    .cta-primary {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      outline: 1px solid red;
    }
    
    .cta-primary .button-group {
      display: flex;
      gap: 10px;
      /* Optional spacing between buttons */
    }
    <div class="cta-primary">
      <div class="button-group">
        <a href="contact" class="btn btn-primary">One</a>
        <a href="contact" class="btn btn-primary">Two</a>
      </div>
    </div>