如何控制 Flexbox 中每列的项目数?

2024-01-09

在弹性容器中,我有 5 个具有列方向的项目,但在一定宽度下,我想每列显示 3 个项目,并强制其他项目换行
有没有办法在没有固定高度的情况下做到这一点?
我的代码:

<div class="container">
    <div class="item-1 item">Item 1</div>
    <div class="item-2 item">Item 2</div>
    <div class="item-3 item">Item 3</div>
    <div class="item-4 item">Item 4</div>
    <div class="item-5 item">Item 5</div>
</div>

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

@media (min-width: 30em) {

}

js Bin: http://jsbin.com/fesujifelu/edit?html,css,输出 http://jsbin.com/fesujifelu/edit?html,css,output


在 Flexbox 中,项目需要容器的高度/宽度限制才能换行。否则,它们就没有断点,将沿着同一条线继续前进。

但你的布局在CSS网格布局中不是问题:

http://jsbin.com/lapafidejo/1/edit?html,css,输出 http://jsbin.com/lapafidejo/1/edit?html,css,output

/* ================================= 
  Flexbox
==================================== */

.container {
  display: grid;
  grid-template-columns: 1fr;
}

/* ================================= 
  Media Queries
==================================== */

@media (min-width: 30em) {
  .container {
    grid-template-rows: 1fr 1fr 1fr;
    grid-auto-columns: 1fr;
    grid-auto-flow: column;
  }
}

/* ================================= 
  Page Styles
==================================== */

* {
  box-sizing: border-box;
}

body {
  font-size: 1.35em;
  font-family: 'Varela Round', sans-serif;
  color: #fff;
  background: #e8e9e9;
  padding-left: 5%;
  padding-right: 5%;
}

.container {
  padding: 10px;
  background: #fff;
  border-radius: 5px;
  margin: 45px auto;
  box-shadow: 0 1.5px 0 0 rgba(0, 0, 0, 0.1);
}

.item {
  color: #fff;
  padding: 15px;
  margin: 5px;
  background: #3db5da;
  border-radius: 3px;
}
<div class="container">
  <div class="item-1 item">Item 1</div>
  <div class="item-2 item">Item 2</div>
  <div class="item-3 item">Item 3</div>
  <div class="item-4 item">Item 4</div>
  <div class="item-5 item">Item 5</div>
</div>

CSS 网格的浏览器支持

  • Chrome - 自 2017 年 3 月 8 日起全面支持(版本 57)
  • Firefox - 自 2017 年 3 月 6 日起全面支持(版本 52)
  • Safari - 自 2017 年 3 月 26 日起全面支持(版本 10.1)
  • Edge - 自 2017 年 10 月 16 日起全面支持(版本 16)
  • IE11 - 不支持当前规范;支持过时版本

这是完整的图片:http://caniuse.com/#search=grid http://caniuse.com/#search=grid


资源:

  • https://css-tricks.com/snippets/css/complete-guide-grid/ https://css-tricks.com/snippets/css/complete-guide-grid/
  • https://gridbyexample.com/examples/ https://gridbyexample.com/examples/
  • https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何控制 Flexbox 中每列的项目数? 的相关文章