"align-items: flex-start"使子项与父项的可用空间对齐



我正在尝试将每个孩子直接对齐(垂直(。显然align-items: flex-start并没有完全做到这一点,因为每个孩子之间都有一些自动间隔。

以下是我得到的结果片段。孩子们沿着父母的可用空间对齐自己,这不是我喜欢实现的目标。我想要的是每个孩子直接对齐其前一个兄弟姐妹之后(垂直对齐,如片段中所示(。

提前感谢!

编辑:flex-flow: column wrapalign-content: flex-start都做到了。但是,我忘记了在最后一个孩子中添加align-self: flex-end,当应用上述两种解决方案中的任何一种时,这都不起作用。

* {
  box-sizing: border-box;
}
#container {
  position: fixed;
  top: 0; right: 0; bottom: 0; left: 0;
  display: flex;
  align-items: flex-start;
  flex-flow: row wrap;
}
#container > div {
  width: 100%;
  margin: 10px;
  border: 2px solid #ff0000;
}
#container > div:nth-child(1) { height: 5%; }
#container > div:nth-child(2) { height: 10%; }
#container > div:nth-child(3) { height: 20%; align-self: flex-end; }
<div id="container">
  <div></div>
  <div></div>
  <div></div>
</div>

您需要在父元素上设置align-content: flex-start,因为初始值为 stretch

伸展

如果沿交叉轴的项的组合大小小于对齐容器的大小,则任何自动调整大小的项目的大小都会相等地增加(不按比例(,同时仍遵守最大高度/最大宽度(或等效功能(施加的约束,以便组合大小正好沿十字轴填充对齐容器。

* {
  box-sizing: border-box;
}
#container {
  position: fixed;
  top: 0; right: 0; bottom: 0; left: 0;
  display: flex;
  align-items: flex-start;
  flex-flow: row wrap;
  align-content: flex-start;
}
#container > div {
  width: 100%;
  margin: 10px;
  border: 2px solid #ff0000;
}
#container > div:nth-child(1) { height: 5%; }
#container > div:nth-child(2) { height: 10%; }
#container > div:nth-child(3) { height: 20%; }
<div id="container">
  <div></div>
  <div></div>
  <div></div>
</div>

更新:另一种解决方案是设置flex-direction: column然后您可以使用margin来定位特定的弹性项目。

* {
  box-sizing: border-box;
}
#container {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  flex-direction: column;
}
#container > div {
  width: calc(100% - 20px);
  margin: 10px;
  border: 2px solid #ff0000;
}
#container > div:nth-child(1) {
  height: 5%;
}
#container > div:nth-child(2) {
  height: 10%;
}
#container > div:nth-child(3) {
  height: 20%;
  margin-top: auto;
}
<div id="container">
  <div></div>
  <div></div>
  <div></div>
</div>

您需要为流设置列

#container {
  position: fixed;
  top: 0; right: 0; bottom: 0; left: 0;
  display: flex;
  align-items: flex-start;
  flex-flow: column wrap;
}
#container > div:nth-child(3) { height: 20%; margin-top: auto; }

更新:

将边距顶部自动添加到最后一个子项

https://jsfiddle.net/qghsgze5/2/

相关内容

最新更新