【问题标题】:Is it possible to ensure buttons are the same within a button group?是否可以确保按钮组中的按钮相同?
【发布时间】:2021-10-26 08:46:44
【问题描述】:

我想确保按钮组中的两个单选按钮占据相同的宽度:

<div class="d-flex btn-group" role="group" aria-label="Basic radio toggle button group">
    <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked>
    <label class="btn btn-outline-primary" for="btnradio1">Text</label>
    <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off">
    <label class="btn btn-outline-primary" for="btnradio2">More Text</label>
</div>

这可能吗?

目前,文本更多的按钮更宽。

谢谢

【问题讨论】:

  • 例如给按钮的类一个max-width:10px; 怎么样?

标签: html css bootstrap-5


【解决方案1】:

对于您的特定设置,我建议您围绕每个 inputlabel 对创建一个容器 div。由于您的 btn-group 上已经有 d-flex,因此您可以使用 flex 属性。

在您的 CSS 中选择 btn-container div,并给它们一个 flex-basis: 100px(您可以将像素值更改为您需要的任何大小)。它们将具有相同的宽度。您还可以使用百分比值,例如,如果您有 4 个按钮,则可以为每个 btn-container 分配一个 flex-basis: 25% 以进行平均分配。

.d-flex {
  display: flex;
}

.btn-container {
  flex-basis: 100px;
}
<link href="https://cdn.bootstrap.css" rel="stylesheet"/>
<div class="d-flex btn-group" role="group" aria-label="Basic radio toggle button group">
    <div class="btn-container">
      <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked/>
      <label class="btn btn-outline-primary" for="btnradio1">Text</label>
    </div>
    <div class="btn-container">
      <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off"/>
      <label class="btn btn-outline-primary" for="btnradio2">More Text</label>
    </div>
</div>

如果您隐藏单选输入并且只显示标签,您可以这样做:

.d-flex {
  display: flex
}

input {
  position: absolute;
  width: 0.01px;
}

label {
  border: 1px solid black;
  padding: 1rem 2rem;
  flex-basis: 50%;
}

input:checked + label {
  background-color: blue;
}
<div class="d-flex btn-group" role="group" aria-label="Basic radio toggle button group">
        <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off">
        <label class="btn btn-outline-primary" for="btnradio1">Text</label>
        <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off">
        <label class="btn btn-outline-primary" for="btnradio2">More Text</label>
</div>

如果您使用的是引导程序,则不需要像我那样在 btn 组中添加额外的样式。只需将 flex 基础放在标签上即可。

【讨论】:

  • 谢谢 - 所以当我尝试这个时,btn-container 的大小是正确的,但输入似乎没有填满容器:jsfiddle.net/c8xg16rb
  • 我也尝试将 w-100 类添加到输入中,但这似乎也不起作用..
  • 好吧,我没有意识到引导程序正在显示这样的按钮。更新了我的回复。
  • 从你的小提琴中删除 btn-container div 就可以了
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2023-04-09
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
相关资源
最近更新 更多