Flexbox的align-self属性会改变div的高度。

6

我有一个像这样的弹性盒设置

.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-end应用于child#2和align-center应用于child#3来将align-self设置为end或center时,它会改变应用它的子元素的高度。 enter image description here 有什么解释为什么会发生这种情况以及可能的解决方法吗?谢谢。

请添加一个带有CSS的工作代码片段,以便您可以在其中定义。您提供的代码未生成与图片中显示的确切情况相同的结果。 - AddWeb Solution Pvt Ltd
这是一个链接到Gist的地址 -- https://gist.github.com/trashvin/edaec01d0b62f6ab193d57cebbd14622 - trashvin
请提供足够的代码以重现问题。 - Michael Benjamin
2个回答

3

如果我们没有指定align属性,它将默认为auto,这将拉伸内容以填充弹性。

auto在绝对定位的元素上计算为本身,在所有其他框上计算为父级上align-items的计算值(减去任何传统关键字),或者如果框没有父级,则为起始位置。其行为取决于布局模型,如justify-self所述。

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

请检查下面的片段。我已经将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>


你对于自动/拉伸的解释帮助我理解了这个问题。我有另一种方法:https://gist.github.com/trashvin/edaec01d0b62f6ab193d57cebbd14622 - trashvin

0

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

https://jsfiddle.net/6xwn80k3/ 查看此 fiddle 并查看在未定义高度的情况下更改子元素 #2 的 align-self 会发生什么。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接