如何在两列布局中先填充右列然后填充左列

RNA*_*RNA 3 css

我有 5 个 div 元素(这里以简化的方式)。如何设置 css 以制作 2 列布局,右侧的前 2 个 div 和左侧的其余 div,如图所示(如果需要,每个 div 元素可以用不同的类或 id 标识)?右侧或左侧的 div 数量可以固定并提前知道,而不是动态飞来飞去。两列可能有不同的高度,但它们需要在顶部对齐(即 div3 和 div1 从相同的垂直位置开始)。理想情况下,我不想在每个 div 元素或左列或右列上设置固定高度。

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Dan*_*eld 5

1) 设置display:flex在容器上

2) 将 flex 容器的主轴设置为块轴flex-direction: column;(参见flex-direction )

3)切换环绕方向flex-wrap: wrap-reverse;(见flex-wrap

注意:这仅在容器具有固定高度时才能正常工作。(感谢@Paulie_D)

演示:

.wpr {
  width: 30vw;
  height: 30vw;
  border: 1px solid;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap-reverse;
  justify-content: space-between;
}
.wpr div {
  width: 45%;
  height: 45%;
  border: 1px solid;
  margin: 1% 1% 1% 6%;
}
.wpr div:nth-child(n+3) {
  height: 30%;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wpr">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>
Run Code Online (Sandbox Code Playgroud)


由于 OP 添加了以下说明:

1) 包装纸可能没有固定的高度

2)右边的div数量可以固定(比如2)

我们可以通过浮动(和清除)前 2 个 div 来实现浮动

.wpr {
  border: 1px solid;
  width: 50vw;
  padding: 1em;
  display: flow-root; /* create new block formatting context */
  /* Note: if ie/edge support is required use overflow: hidden
           instead of display: flow-root */
}
.wpr div {
  color: green;
  border: 1px solid;
  margin: 0.3em;
  padding: 1em;
  width: 35%;
}
.wpr div:nth-child(-n + 2) {
  color: red;
  float: right;
  clear: right;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wpr">
  <div>1 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard </div>
  <div>2 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type </div>
  <div>3 Lorem Ipsum is simply dummy when an unknown printer took a g </div>
  <div>4 Lorem Ipsum is simply dummy text of the printing </div>
  <div>5 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem  </div>
</div>
Run Code Online (Sandbox Code Playgroud)