如何使 Flexbox 容器自动调整宽度并居中且按钮彼此相邻对齐?

问题描述 投票:0回答:1

我使用以下代码,但容器仍然是全宽

我希望它能够适应其内容的宽度

.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>

我尝试过

width: auto
但没有什么区别

html css twitter-bootstrap flexbox width
1个回答
0
投票

您必须使其

inline-flex
,然后使用任何适当的方法将其在其父级上居中。

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>

© www.soinside.com 2019 - 2024. All rights reserved.