Flexbox align-self正在改变div的高度

时间:2017-12-14 06:39:24

标签: css flexbox

我有像这样的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>

enter image description here

问题是,当我尝试将align-self设置为end-end时,将align-end应用于child#2并将align-center设置为child#3,它会改变应用它的子项的高度。 enter image description here

为什么会出现这种情况以及可能的解决办法?感谢

2 个答案:

答案 0 :(得分:2)

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

  

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(取内容高度)。

请查看以下代码段。我已将align-self应用于所有孩子,然后将第二个孩子的值更改为stretch

&#13;
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

align-self的默认值为auto,这意味着它将获得父Flex容器的align-items,其默认值为stretch,因为子#2有一个max-height:50px,它最多只能拉伸50px。当您将align-self值更改为其他内容时,子级#2不会伸展,其height可能会获得其min-height或其子级的高度。

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