【问题标题】:CSS: Items at the bottom of parent elementCSS:父元素底部的项目
【发布时间】:2018-10-18 01:09:49
【问题描述】:

对于特定的弹性项目,我可以用 align-self: flex-end 覆盖 align-items: flex-start,有没有办法覆盖 justify-content 特定的弹性项目?

我有一个包含三个子项目的盒子,我需要在盒子底部 (flex_wrapper) 的最后一个项目 (item-3)

喜欢这张图片:

请检查我的代码:

.item-1{
  background: red;
}

.item-2{
  background: blue;
}

.item-3{
  background: yellow;
}


.flex_wrapper{
  background: #ddd;
  width: 400px;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.flex_items{
  padding: 10px;
}
<div class="flex_wrapper">
    <div class="flex_items item-1">Item 01</div>
    <div class="flex_items item-2">Item 02</div>
    <div class="flex_items item-3">Item 03</div>
</div>

注意:可以通过使用 margin 属性或 position 属性, 但我必须使用 flex-box。

【问题讨论】:

  • 为什么不用 margin-top:auto ?它也是弹性盒

标签: html css flexbox


【解决方案1】:

是的,这个其实很简单,只要在底部margin-top:auto给出你想要的元素即可。不需要包装器或额外的元素。

.item-3{

  margin-top:auto;
}

.item-1 {
  background: red;
}

.item-2 {
  background: blue;
}

.item-3 {
  background: yellow;
  margin-top: auto;
}

.flex_wrapper {
  background: #ddd;
  width: 400px;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.flex_items {
  padding: 10px;
}
<div class="flex_wrapper">
  <div class="flex_items item-1">Item 01</div>
  <div class="flex_items item-2">Item 02</div>
  <div class="flex_items item-3">Item 03</div>
</div>

【讨论】:

    【解决方案2】:

    您需要在flex-grow: 1 之间添加一个不可见的项目以占据空间并将您的第三个项目向下推:

    .item-1{
      background: red;
    }
    
    .item-2{
      background: blue;
    }
    
    .item-3{
      background: yellow;
    }
    
    
    .flex_wrapper{
      background: #ddd;
      width: 400px;
      height: 300px;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
    }
    
    .flex_items{
      padding: 10px;
    }
    
    .separator {
      flex-grow: 1;
    }
    <div class="flex_wrapper">
        <div class="flex_items item-1">Item 01</div>
        <div class="flex_items item-2">Item 02</div>
        <div class="separator"></div>
        <div class="flex_items item-3">Item 03</div>
    </div>

    【讨论】:

    • @DelowarHosain 不,先生! margin-top: 0 很好用,grid 可以,但是 flex 不行,它是一维系统
    • 如果您只有 2 个项目,则可以使用 justify-content: space-between;,但不能超过 2 个
    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    相关资源
    最近更新 更多