2

https://codepen.io/leon-yum/pen/XYpgzj?editors=1100

我试图确保在移动设备(400px 及以下)上,我的 flexbox 网格坚持 2 cols / box。但是无论我做什么,它要么捕捉到 1 列,要么每行分别保持在 3 列或 4 列。

预计宽度为 400 像素:

在此处输入图像描述

结果:

在此处输入图像描述

HTML

<div class="flex-grid-thirds">
  <div class="col">This little piggy went to market.</div>
  <div class="col">This little piggy stayed home.</div>
  <div class="col">This little piggy had roast beef.</div>
</div>

<div class="flex-grid-four">
  <div class="col">This little piggy went to market.</div>
  <div class="col">This little piggy stayed home.</div>
  <div class="col">This little piggy had roast beef.</div>
  <div class="col">This little piggy had roast beef.</div>
</div>

CSS

.flex-grid-thirds,
.flex-grid-four {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.flex-grid-thirds .col {
  width: 32%;
}

.flex-grid-four .col {
  width: 24%;
}

@media (max-width: 400px) {
  .flex-grid-thirds,
  .flex-grid-four {
    .col {
      width: 40%;
    }
  }
}

* {
  box-sizing: border-box;
}
body {
  padding: 20px;
}
.flex-grid { 
  margin: 0 0 20px 0;
}
.col {
  background: salmon;
  padding: 20px;
}
4

1 回答 1

1

这是有效的解决方案:https ://codepen.io/anon/pen/vrgZVa?editors=1100 。您所需要的只是将所有项目放在一个包装器元素中(现在您有 2 个元素),并flex-wrap: wrap为该包装器提供属性。还有一件事要做:为您的项目指定宽度(最好是百分比),如果您愿意width: 50%,将有 2 列,如果width: 33%- 3 列,依此类推。我没有触及边距和这么小的东西,只是展示你的要求:

.flex-grid {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.flex-grid-thirds .col {
  width: 32%;
}

.flex-grid-four .col {
  width: 24%;
}

@media (max-width: 400px) {
  .flex-grid {
    .col {
      width: 50%;
    }
  }
}

* {
  box-sizing: border-box;
}

body {
  padding: 20px;
}
.flex-grid { 
  margin: 0 0 20px 0;
}
.col {
  background: salmon;
  padding: 20px;
}
<div class="flex-grid">
  <div class="col">This little piggy went to market.</div>
  <div class="col">This little piggy stayed home.</div>
  <div class="col">This little piggy had roast beef.</div>
  <div class="col">This little piggy went to market.</div>
  <div class="col">This little piggy stayed home.</div>
  <div class="col">This little piggy had roast beef.</div>
  <div class="col">This little piggy had roast beef.</div>
</div>

于 2018-06-09T17:20:05.147 回答