首页 > 解决方案 > 使用 FlexBox(或其他 css),是否可以在每行中拥有不同数量的相同大小的列(即不使用空 div)?

问题描述

我正在寻找一个 2 行的网格 - row1 有 2 列,row2 有 3 列,其中每列/行(即网格中的项目)大小相同。它使用空 div 工作,但显然这不是首选解决方案....

我已经包含了一些基本的示例 html / css 来说明我的意思,但我想在不使用空 div 的情况下实现这样的目标......

CSS

html, body {
  height: 100%;
  margin: 0;
}

.grid {
  min-height: 100%;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
}

.grid > div {
  display: flex; 
  flex-basis: calc(33.33% - 14px);  
  justify-content: center;
  flex-direction: column;
}

.grid > div > div {
  display: flex;
  justify-content: center;
  flex-direction: row;
}

.box { margin: 10px 0 10px 10px}
.box1 { background-color: red; }
.box2 { background-color: orange; }
.box3 { background-color: blue; }
.box4 { background-color: grey; }
.box5 { background-color: purple; }

HTML

<div class="grid">
  <div class="box box1">
    <div>
      one
    </div>
    <div>
      example content
    </div>    
  </div>
 <div class="box box2">
   <div>
     two
   </div>
   <div>
     example content
   </div> 
 </div>
 <div></div>
 <div class="box box3">
   <div>
     three
   </div> 
 </div>
 <div class="box box4">
   <div>
     four
   </div> 
 </div>
 <div class="box box5">
   <div>
     five
   </div> 
 </div>

标签: htmlcsslayoutflexboxgrid

解决方案


与之前的空间

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container{
  width: 1000px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, auto);
  grid-gap: 1px;
}
.container > div{
  background-color: orangered;
  height: 50px;
}
.box1{
  grid-column: 2 / 3;
}
<div class="container">
<div class="box1">box 1</div>
<div class="box2">box 2</div>
<div class="box3">box 3</div>
<div class="box4">box 4</div>
<div class="box5">box5</div>
</div>

后面有空间

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container{
  width: 1000px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, auto);
  grid-gap: 1px;
}
.container > div{
  background-color: orangered;
  height: 50px;
}
.box3{
  grid-column: 1 / 2;
}
<div class="container">
<div class="box1">box 1</div>
<div class="box2">box 2</div>
<div class="box3">box 3</div>
<div class="box4">box 4</div>
<div class="box5">box5</div>
</div>


推荐阅读