【问题标题】:Getting flex to have equal width columns to the widest element让 flex 具有与最宽元素相等宽度的列
【发布时间】:2018-12-10 05:23:22
【问题描述】:

我有一堆按钮,我希望它们都具有相同的宽度,而不必设置特定的宽度,所以自然你会希望 all 按钮的宽度取最广泛的元素,但我很难用 flex 实现这一点,因为它似乎只是希望它们都是 100%;我还尝试在锚点周围使用包装器,但这并没有帮助,因为按钮的宽度都不同。

CodePen: https://codepen.io/gutterboy/pen/MZWroj?editors=1100

因此,在该示例中,所有按钮都应与“Groundskeeping”的自然宽度相匹配。

HTML:

<div class="container">
  <div class="row">
    <div class="offset-md-4 col-md-4">
<div class="buttons">
    <a href="" class="btn alt">Plumbing</a>
    <a href="" class="btn alt">Electrical</a>
    <a href="" class="btn alt">Groundskeeping</a>
    <a href="" class="btn alt">Construction</a>
    <a href="" class="btn alt">Cleaning</a>
    <a href="" class="btn alt">Security</a>
    <a href="" class="btn alt">Trades Assistant</a>
    <a href="" class="btn alt">General Duties</a>
</div>      
    </div>
  </div>
</div>

CSS:

.buttons {
    display: flex;
    flex-direction: column;
  padding: 15px;
    background-color: gray;

    .btn {
        display: block;
        margin-bottom: 11px;

        &:last-child {
            padding-bottom: 21px;
        }

    }

}

a.btn {
    display: inline-block;
    text-align: center;
    height: 35px;
    padding: 0 20px;
    min-width: 128px;
    font-weight: bold;
    color: #fff;
    background-color: orange;
    border: 2px solid #000;
    white-space: nowrap;
    text-decoration: none;
}

有什么方法可以在 Flex 或其他任何东西中完成吗?

【问题讨论】:

标签: html css flexbox


【解决方案1】:

你差不多好了,你应该使用inline-flex而不是flex来进行收缩以适应行为,因此最大的按钮将定义容器的宽度,所有元素默认拉伸到该宽度:

.container {
  margin-top: 15px;
  text-align:center;
}

.buttons {
  display: inline-flex;
  flex-direction: column;
  padding: 15px;
  background-color: gray;
}

.buttons .btn {
  display: block;
  margin-bottom: 11px;
}

.buttons .btn:last-child {
  padding-bottom: 21px;
}

a.btn {
  display: inline-block;
  text-align: center;
  height: 35px;
  padding: 0 20px;
  min-width: 128px;
  font-weight: bold;
  color: #fff;
  background-color: orange;
  border: 2px solid #000;
  white-space: nowrap;
  text-decoration: none;
}
<div class="container">

  <div class="buttons">
    <a href="" class="btn alt">Plumbing</a>
    <a href="" class="btn alt">Electrical</a>
    <a href="" class="btn alt">Groundskeeping</a>
    <a href="" class="btn alt">Construction</a>
    <a href="" class="btn alt">Cleaning</a>
    <a href="" class="btn alt">Security</a>
    <a href="" class="btn alt">Trades Assistant</a>
    <a href="" class="btn alt">General Duties</a>
  </div>

</div>

【讨论】:

  • 有没有办法从确定组的宽度中排除一行?例如第一行有更多的文本,应该被换行,但宽度仍然来自其他最大的?
  • @user3104267 将width:0;min-width:100% 应用于要排除的元素(相关:stackoverflow.com/a/55041133/8620333
猜你喜欢
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
  • 2020-11-30
  • 2014-09-23
  • 1970-01-01
相关资源
最近更新 更多