html - 使 flex 元素换行到下一行,以下元素继续流动

标签 html css flexbox

我希望红色框位于第二行,但我希望在它之后定义的 div 在第一行继续,这样所有的黑框基本上都环绕在黑框周围。这可以用 flexbox 实现吗?

它应该是这样的:

+---+---+---+---+---+
| 1 | 2 | 3 | 5 | 6 |
+---+---+---+---+---+
|         4         |
+---+---+---+---+---+
| 7 | 8 | 9 |10 |11 |
+---+---+---+---+---+
|12 |13 |
+---+---+

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.a {
  border: 1px solid black;
  height: 50px;
  width: 20%;
}

.b {
  border: 1px solid red;
  height: 50px;
  width: 100%;
}
<div class="container">
  <div class='a'>1</div>
  <div class='a'>2</div>
  <div class='a'>3</div>
  <div class='b'>4</div>
  <div class='a'>5</div>
  <div class='a'>6</div>
  <div class='a'>7</div>
  <div class='a'>8</div>
  <div class='a'>9</div>
  <div class='a'>10</div>
  <div class='a'>11</div>
  <div class='a'>12</div>
  <div class='a'>13</div>
</div>

参见 https://codepen.io/anon/pen/OqqeJN

最佳答案

使用 CSS 网格来完成此任务会更好:

* {
  box-sizing: border-box;
}

.container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-auto-flow: dense; /* this will make the elements to flow around*/
}

.a {
  border: 1px solid black;
  height: 50px;
}

.b {
  border: 1px solid red;
  height: 50px;
  /*full width row*/
  grid-column: 1/-1;
}
<div class="container">
  <div class='a'>1</div>
  <div class='a'>2</div>
  <div class='a'>3</div>
  <div class='b'>4</div>
  <div class='a'>5</div>
  <div class='a'>6</div>
  <div class='a'>7</div>
  <div class='a'>8</div>
  <div class='a'>9</div>
  <div class='a'>10</div>
  <div class='a'>11</div>
  <div class='a'>12</div>
  <div class='a'>13</div>
</div>

dense

If specified, the auto-placement algorithm uses a “dense” packing algorithm, which attempts to fill in holes earlier in the grid if smaller items come up later. This may cause items to appear out-of-order, when doing so would fill in holes left by larger items.ref

关于html - 使 flex 元素换行到下一行,以下元素继续流动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55344983/

相关文章:

javascript - Bootstrap 3 Collapse - 添加事件类以打开面板

css - Bootstrap 脚本和样式不起作用

html - 在第四个之后截断操作栏元素

html - 如何使网页中的元素不被打印?

javascript - 从网页打印选定的数据

javascript - 选择时填写下拉列表

html - Flex - child 固定位置和 100% 高度

html - 无法将 Css 应用到我的 ASP :Label

html - 当span用于包含一个&lt;input type ="text">时,为什么span默认设计成宽度小于其父元素的宽度

html - flex 元素 25% 高度