首页 > 解决方案 > Flexbox - 需要获得不同高度的单个 div 框的水平行,以便垂直地相互坐下

问题描述

根据标题,我有一个循环遍历数组的 for 循环,并创建几个 div 框(每行四个),每个 div 都有自己独特的垂直高度。发生的事情是,第二、第三等行将从其上方行中最高 div 的位置开始。我希望将第二、第三等行上的 div 垂直向上推到其上方行中的 div 上,但这并没有发生。最高的 div 挡住了整行,而下一行的任何内容都自动位于该 div 下方。我想通过 flex-box 做到这一点,所以我认为 align-content: flex-start; 所有单个 div 框的父容器上的命令都会为我执行此操作,但它不起作用。

HTML:

 <div class="pasteContainerAll">

   <div class="centreLoadSpinner" v-if="pasteList.length === 0">
           <div class="lds-spinner" style="100%;height:100%;margin-auto"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
      </div>
  </div>



 <div class="pasteContainerEach" v-else  v-for="paste in pasteList" :key="paste.id"> 
   <div class="pasteTitleContainer"><router-link :to="{ name: 'EditPaste',  params: {paste_slug: paste.slug}}"><i class="far fa-edit"></i></router-link>
   {{ paste.title }} <i class="far fa-trash-alt" @click="deletePaste(paste.slug)"></i> </div>
   <textarea-autosize readonly class="pasteContentTextarea" v-model="paste.content" v-on:click.native="copyContent(paste.content)"></textarea-autosize> 
  </div>


 </div>

CSS:

.pasteContainerAll
{
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  align-content: flex-start;
}

.centreLoadSpinner
{
  display: flex;
  justify-content: center;
  width: 100%;
}

.pasteContainerEach
{
  width: 24%;
  margin-left: 0.5%;
  margin-right: 0.5%;
  margin-bottom: 1%;
  box-sizing: border-box;
}

.pasteTitleContainer
{
  margin-bottom: 4px;
  display: flex;
  width: 100%;
  font-size: 1rem;
  justify-content: space-between;
}

.pasteContentTextarea
{
  font-size: 1rem;
  width: 100%;
  resize: none;
  cursor: pointer;
  padding: 0;
  box-sizing: border-box;
  border: 0;
  font-family: 'Roboto', sans-serif;
}

标签: htmlcssflexbox

解决方案


与其考虑在 div 的高度不同时尝试让行相互对接 - 翻转轴并使用 flex 将 div 呈现在列中。

此解决方案将不同高度的 div 嵌套在列内,但每一列都被视为一行的一部分。使用 flex 的好处是它会自动平均分配内容。

我只是使用奇偶样式来证明这一点 - 但它显示了您正在寻找的砖石联锁砖。这只是意味着重新处理数据以稍微不同的方式呈现。

通过翻转轴 - 每列中的第一个 div 创建第 1 行,每列中的第二个 div 创建第 2 行,依此类推。

.wrapper {
  display: flex; 
 }
 
div {
  min-height: 50px;
  background-color: yellow;
  border: solid 1px #222;
  flex:1;
}

.column1 > div:nth-of-type(odd),
.column3 > div:nth-of-type(odd){
  height: 80px;
 }
 
 .column2 > div:nth-of-type(even),
 .column4 > div:nth-of-type(even){
  height: 80px;
 }
 
 div > div:nth-of-type(odd){background: aqua}
<div class="wrapper">
  <div class="column1">
    <div> Row 1</div>
    <div> Row 2</div>
    <div> Row 3</div>
    <div> Row 4</div>
  </div> 
  <div class="column2">
    <div> Row 1</div>
    <div> Row 2</div>
    <div> Row 3</div>
    <div> Row 4</div>
  </div>
  <div class="column3">
    <div> Row 1</div>
    <div> Row 2</div>
    <div> Row 3</div>
    <div> Row 4</div>
  </div>
    <div class="column4">
    <div> Row 1</div>
    <div> Row 2</div>
    <div> Row 3</div>
    <div> Row 4</div>
  </div>
</div>


推荐阅读