在flex容器中进行flex-wrap不会使容器的宽度变大

时间:2018-08-27 19:28:50

标签: html css css3 flexbox

所以我要求3个元素块看起来像这样:

enter image description here

没有垂直滚动,只有水平滚动。为此,我想我可以使用容器div.block制作3个display: flex,然后将每个.block内的物品弯曲并包裹起来(注意它们也需要上下左右)所以flex-direction: column

但是正如您在这段代码(或codepen)中所看到的那样,当我这样做时,即使.block的3个.brick的宽度只是拒绝扩展为其内容的宽度}确实将它们彼此重叠,因为.block`保持与单个列一样大。

我该如何实现?我觉得flex不是用于容器的正确工具,但是我尝试了display: inline-block并使用table和3个td来完成相同的操作。

我不确定如何随着更多内容的加入而使.container的宽度增加,以及如何使.block的宽度也增加。

.container {
  width: 600px;
  height: 200px;
  overflow-x: auto;
  overflow-y: hidden;
  display: flex;
}

.block {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.brick {
  width: 100px;
  height: 50px;
  margin: 5px;
}

.brick-red {
  background: red;
}
  
.brick-blue {
  background: blue;
}
  
.brick-orange {
  background: orange;
}
<div class="container">
  <div class="block">
    <div class="brick brick-red"></div>
    <div class="brick brick-red"></div>
    <div class="brick brick-red"></div>
    <div class="brick brick-red"></div>
    <div class="brick brick-red"></div>
    <div class="brick brick-red"></div>
    <div class="brick brick-red"></div>
  </div>
  <div class="block">
    <div class="brick brick-blue"></div>
    <div class="brick brick-blue"></div>
    <div class="brick brick-blue"></div>
    <div class="brick brick-blue"></div>
    <div class="brick brick-blue"></div>
  </div>
  <div class="block">
    <div class="brick brick-orange"></div>
    <div class="brick brick-orange"></div>
    <div class="brick brick-orange"></div>
    <div class="brick brick-orange"></div>
    <div class="brick brick-orange"></div>
  </div>
</div>

1 个答案:

答案 0 :(得分:-2)

您需要将width或flex-basis设置为内容的总宽度(包括边距),并将flex-shrink设置为0。

尝试设置

composer require <bundlename>

.block {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  flex: 0 0 calc(110px * 3); 
  //calc can be replaced with a fixed value if you're doing a px based approach
}
.container {
  width: 400px;
  height: 200px;
  overflow-x: auto;
  overflow-y: hidden;
  display: flex;
}

.block {
  height: 100%;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  flex: 1 0 calc(110px * 3);
}

.brick {
  width: 100px;
  height: 50px;
  margin: 5px;
}

.brick-red {
  background: red;
}

.brick-blue {
  background: blue;
}

.brick-orange {
  background: orange;
}