【问题标题】:How can I control the number of items per column in flexbox?如何控制 flexbox 中每列的项目数?
【发布时间】:2017-10-30 00:26:45
【问题描述】:

在 flex 容器中,我有 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斌:http://jsbin.com/fesujifelu/edit?html,css,output

【问题讨论】:

  • @Michael_B 非常感谢

标签: html css flexbox css-grid


【解决方案1】:

在 flexbox 中,项目需要对容器进行高度/宽度限制才能换行。否则,它们将没有断点,并且将沿同一行继续。

但是你的布局在 CSS Grid Layout 中不是问题:

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


资源:

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2019-09-15
    • 1970-01-01
    • 2018-07-03
    • 2020-12-09
    • 2021-01-01
    • 2021-08-09
    • 1970-01-01
    • 2017-12-15
    相关资源
    最近更新 更多