【问题标题】:Align items top and bottom inside same container在同一个容器内对齐项目的顶部和底部
【发布时间】:2016-12-14 16:48:17
【问题描述】:

我在一个容器里有一些物品,有黑色和红色的物品:

<div class="container">
  <div class="item black"></div>
  <div class="item black"></div>
  <div class="item red"></div>
  <div class="item red"></div>
  <div class="item black"></div>
  <div class="item red"></div>
</div>

我想在不修改 HTML 代码的情况下,在 CSS 中将黑色项对齐顶部,红色项对齐底部。

这是一个用于实验的 jsfiddle https://jsfiddle.net/e72c99c0/

【问题讨论】:

  • 黑色和红色物品的数量是可变的还是固定的?

标签: css flexbox vertical-alignment


【解决方案1】:

您可以使用 order 对项目进行分组,并使用 margin-bottom:auto 将一组固定到底部。

.container {
  height: 300px;
  width: 40px;
  background: #ddd;
  display: flex;
  flex-direction: column;
}

.item {
  width: 40px;
  height: 20px;
  margin-bottom: 1px;
  border: 1px solid #aaa;
}

.item.black {
  background: #222;
  
}

.black:nth-of-type(5) {
  margin-bottom: auto ;
}

.item.red {
  background: red;
  order:2;
}
<div class="container">
  <div class="item black"></div>
  <div class="item black"></div>
  <div class="item red"></div>
  <div class="item red"></div>
  <div class="item black"></div>
  <div class="item red"></div>
</div>

【讨论】:

  • 效果很好!!相反,我将黑色项目重新排序到顶部,然后使用.black + .red { margin-top: auto; }。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多