html - Flexbox 行左对齐

标签 html css flexbox

<分区>

我正在尝试使用 flexbox 创建一个网格,但我无法让最后一行元素左对齐,因为我正在使用 justify-content: space-between。我在下面添加了一个 JS Fiddle: <强> https://jsfiddle.net/b5f4jmhu/

当没有 4 个框组成一整行时,最后一行空格中的框。当没有足够的框来填充行时,关于如何使最后一行左对齐有什么建议吗?

.boxes {
  max-width: 600px;
  background: #ccc;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 20px 20px 0 20px;
  margin: 60px auto 60px auto;
}

.box {
  flex: 0 0 22%;
  height: 100px;
  background: #222;
  margin: 0 0 20px 0;
}
<div class="boxes">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

谢谢, 杰米

最佳答案

使用 flex 你不能选择最后一行,但是对于每行上已知数量的元素,你可以计算它们并在需要时重置最后一个元素的右边距。

此处它将从 4 组中定位 2 和 3。:last-chld:nth-child(xn) 将帮助您选择这两个(可能性)。

例子:

.boxes {
  max-width: 600px;
  background: #ccc;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 20px 20px 0 20px;
  margin: 60px auto 60px auto;
}

.box {
  flex: 0 0 22%;
  height: 100px;
  background: #222;
  margin: 0 0 20px 0;
}
.box:last-of-type:nth-child(4n - 1) {
  margin-right:calc(22% + 24px);/* size of one element + its margin */
}
.box:last-of-type:nth-child(4n - 2) {
  margin-right:calc(44% + 48px);/* size of two elements + their margin */
}
<div class="boxes">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
<div class="boxes">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

<div class="boxes">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

如果网格是处理这个问题的更好方法,那么在使用 flex 时有一个解决方案。

关于html - Flexbox 行左对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57275440/

相关文章:

html - Firefox 中的 Flex 会自动缩小图像,但 Chrome 中不会

javascript - 隐藏不属于某个类的元素

html - 带有透明背景的webkit滚动条

javascript - Firefox 中的 Accordion 链接坏了?

react-native - 在 react native 的 ListView 中并排渲染两个项目(图像)

css - 在 Explorer 和 Safari 中调整内容

javascript - Video.js:初始化前如何判断当前设备是否有原生播放?

html - Internet Explorer 上的 CSS 错误阴影效果(纸张 curl )

html - 在未知宽度的父容器中集中对齐固定宽度的子元素

html - 连续的 div 在桌面模式下不集中