This question already has answers here:
What are the differences between flex-basis and width?

(5 个回答)


3年前关闭。




我在使用 flexbox 时遇到问题,我试图让我的第一个 .cell1 承担其中 3 个元素的宽度,所以它应该是 300px 宽,所以我已将其设置为 flex: 0 0 auto 并将 .cell2 设置为 flex: 1 所以它占用了剩余的空间,但它似乎与 .cell1 重叠,而不是这样做,我不知道为什么?

我怎样才能让 .cell1 占据其中 3 个元素的宽度,而 .cell2 占据剩余的宽度?

.wrap {
  display:flex;
  flex-wrap:wrap;
  width: 100%;
}

.cell1{
  display:flex;
  flex: 0 0 auto;
  flex-direction: row;
}
.cell2{
  display: flex;
  flex: 1;
  background: #ff0000;
}
.item1{
  flex: 0 0 100px;
  background: #ff0000;
}

.item2{
  flex: 0 0 100px;
  background: #0000ff;
}

.item3{
  flex: 0 0 100px;
  background: #ff00ff;
}
<div class="wrap">
  <div class="cell1">
    <div class="item1">
    item 1
    </div>
    <div class="item2">
    item 2
    </div>
    <div class="item3">
    item 3
    </div>
  </div>

  <div class="cell2">
  cell2
  </div>
</div>

最佳答案

使用 width 而不是 flex-basis 。这是一个已知错误,您可以在此处阅读更多信息:

What are the differences between flex-basis and width?(@Michael_B 接受的答案末尾)



.wrap {
  display:flex;
  flex-wrap:wrap;
  width: 100%;
}

.cell1{
  display:flex;
  flex-direction: row;
}
.cell2{
  display: flex;
  flex: 1;
  background: #ff0000;
}
.item1{
  width:100px;
  background: #ff0000;
}

.item2{
  width:100px;
  background: #0000ff;
}

.item3{
  width:100px;
  background: #ff00ff;
}
<div class="wrap">
  <div class="cell1">
    <div class="item1">
    item 1
    </div>
    <div class="item2">
    item 2
    </div>
    <div class="item3">
    item 3
    </div>
  </div>

  <div class="cell2">
  cell2
  </div>
</div>

关于html - 在 flexbox 中设置元素的初始宽度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49066012/

10-12 01:13
查看更多