首页 > 解决方案 > 具有四个 div 的 Flex 容器,需要三列,第二列有两行

问题描述

对于页面上的一个部分,我试图显示两个矩形 div 在两侧的两个方形 div 之间堆叠,与两个堆叠 div 的高度一样大,这些 div 内部是 img 标签。

我正在使用这个标记,因为在移动设备上,我希望能够将它们放在带有overflow: hidden父级的未包装的 flex 行上,这样我就可以使用滑动代码来平移 X 轴。我在使用 flexbox 使用此标记为桌面创建此布局时遇到问题(无网格,需要支持 IE11)。有人用这个标记做过这个布局吗?谢谢。

 <div class="flex_container">
   <div class='flex_child square'>
     <img...>
   </div>
   <div class='flex-child rect'>
     <img...>
   </div>
   <div class='flex-child rect'>
     <img...>
   </div>
   <div class='flex-child square'>
     <img...>
   </div>
 </div>

图片示例

标签: htmlcssflexboxgrid-layout

解决方案


假设这将是您页面的主要布局,您可以尝试设置固定高度并使用 flexbox 的列方向:

.flex_container {
  height: 100vh; /*adjust this value like you want*/
  display: flex;
  flex-direction: column;
  flex-wrap:wrap;
}
.flex_child {
  background:purple;
  border:2px solid #fff;
  box-sizing:border-box;
  width:calc(100% / 3);
}
.square {
  flex:1 1 100%;
}
.rect {
  flex:1 1 47%;
}

body {
  margin: 0;
}
<div class="flex_container">
  <div class='flex_child square'></div>
  <div class='flex_child rect  '></div>
  <div class='flex_child rect  '></div>
  <div class='flex_child square'></div>
</div>

如果您想要更好的浏览器支持,您可以通过稍微调整在开始时制作 2 个正方形的类来使用浮动/内联块:

.flex_container {
  height: 100vh; /*adjust this value like you want*/
}
.flex_child {
  background:purple;
  border:2px solid #fff;
  box-sizing:border-box;
  width:calc(100% / 3);
  height:100%;
}
.square:nth-child(1) {
  float:left;
}
.square:nth-child(2) {
  float:right;
}
.rect {
  display:inline-block;
  height:50%;
  vertical-align:top;
}

body {
  margin: 0;
}
<div class="flex_container">
  <div class='flex_child square'></div>
  <div class='flex_child square'></div>
  <div class='flex_child rect  '></div>
  <div class='flex_child rect  '></div>
</div>

如果您也不能更改类,请使用一些负边距来纠正最后一个元素的位置:

.flex_container {
  height: 100vh; /*adjust this value like you want*/
}
.flex_child {
  background:purple;
  border:2px solid #fff;
  box-sizing:border-box;
  width:calc(100% / 3);
  height:100%;
}
.square:first-child {
  float:left;
}
.square:last-child {
  float:right;
  margin-top:-50vh;
}
.rect {
  display:inline-block;
  height:50%;
  vertical-align:top;
}

body {
  margin: 0;
}
<div class="flex_container">
  <div class='flex_child square'></div>
  <div class='flex_child rect  '></div>
  <div class='flex_child rect  '></div>
  <div class='flex_child square'></div>
</div>


推荐阅读