【问题标题】:Flexbox align-self is changing the div's heightFlexbox align-self 正在改变 div 的高度
【发布时间】:2017-12-14 06:39:23
【问题描述】:

我有一个这样的 flexbox 设置

.container {
display: flex;
min-height: 300px !important;
}
.space-between {
justify-content: space-between;
}
.align-end {
align-self: flex-end;
}
.align-center {
    align-self: center;
}

<div class="container space-between">
        <div class="child" style="max-height: 100px"></div>
        <div class="child yellow-div" style="max-height: 50px"></div>
        <div class="child blue-div" style="max-height: 150px"></div>
        <div class="child pink-div"></div>
</div>

问题是,当我尝试通过将 align-end 应用于 child#2 并将 align-center 应用于 child#3 来将 align-self 设置为 end 或 center 时,它会更改正在应用它的孩子的高度。

任何解释为什么会发生这种情况以及可能的解决方法?谢谢

【问题讨论】:

标签: css flexbox


【解决方案1】:

除非我们指定一些 align 属性,否则它将默认为 auto,这将拉伸内容以填充 flex,

auto computes to itself on absolutely-positioned elements, and to the computed value of align-items on the parent (minus any legacy keywords) on all other boxes, or start if the box has no parent. Its behavior depends on the layout model, as described for justify-self.

因此,在您的情况下,一旦您更改了 align 属性,如果没有应用特定高度,它会将其高度更改为 auto(采用内容高度)。

请检查下面的sn-p。我已将align-self 应用于所有孩子的值,然后将第二个孩子的值更改为stretch

.container {
display: flex;
min-height: 300px !important;
}
.space-between {
justify-content: space-between;
}
.child{
 width: 100px; 
 border: 1px dotted red;
 align-self: baseline;
}
.align-end {
align-self: flex-end;
}
.align-center {
    align-self: center;
}
.yellow-div{
  background: yellow;
  align-self: flex-end;
}
.yellow-div+div{
  align-self: stretch;
}
.blue-div{
  background: blue;
  align-self: center;
}
.pink-div{
  background: pink;
}
<div class="container space-between">
        <div class="child yellow-div" style="max-height: 50px"></div>
        <div class="child" style="max-height: 100px"></div>
        <div class="child blue-div" style="max-height: 150px"></div>
        <div class="child pink-div"></div>
</div>

【讨论】:

【解决方案2】:

align-self 的默认值为auto,这意味着它将获得默认值为stretch 的父flex 容器的align-items,并且由于child#2 有一个max-height:50px,它只能拉伸高达 50 像素。当您将 align-self 值更改为其他值时,child#2 不会拉伸,它的 height 可能会得到它的 min-height 或它的孩子的高度。

https://jsfiddle.net/6xwn80k3/ 检查这个小提琴,看看当你更改 child#2 的align-self 时会发生什么,而没有定义高度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-14
    • 2013-05-21
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 2020-03-22
    相关资源
    最近更新 更多