首页 > 解决方案 > 以不同顺序使用 div 的 flex 进行 CSS 定位

问题描述

我正在尝试使用 Flexbox 获得特定的 css 布局(作为 css 网格布局的后备),但实际上我不确定是否有可能获得我的想法。

我有以下 HTML 结构:

<div class="container">
    <div class="div1">DIV 1</div>
    <div class="div2">DIV 2</div>
    <div class="div3">DIV 3</div>
</div>

这就是我想要实现的(使用 css 网格很容易):

在此处输入图像描述

除此之外,我希望 div 1 和 3 固定在滚动上,并且 div2 内容可以滚动。

我只是想知道是否有可能完成这项工作;我尝试了许多弹性设置,但我无法获得它。

标签: htmlcssflexboxcss-grid

解决方案


If your container has a fixed height (I'm assuming it is 100% of the viewport), you can use column direction with wrap and order to achieve your layout:

html, body {
  margin:0;
  height:100%;
  color:white;
}
.container {
  height:100%;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.div1,
.div3 {
  height: 50%;
  width: 30%;
}

.div1 {
  background: red;
}

.div2 {
  max-height:100%; /* make overflow scroll */
  overflow:auto;
  flex-grow: 1;  /* make div fill height */
  width: 70%;
  order: 3;      /* put this div at the end */
  background: grey;
}

.div3 {
  order: 2;       /* put this div below div1 */
  background: blue;
}
<div class="container">
  <div class="div1">DIV 1</div>
  <div class="div2">DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br></div>
  <div class="div3">DIV 3</div>
</div>


推荐阅读