防止展开Flex项目高度以匹配其他Flex项目 [英] Prevent a flex items height from expanding to match other flex items
问题描述
.flexbox-2
)上,我将它设置为CSS的高度。但是,第一个元素( .flexbox-1
)将匹配 .flexbox-2
的高度。我将如何阻止 .flexbox-1
匹配 .flexbox-2
的高度,而不是保留其自然高度? 这是我到目前为止(也可以用作为jsFiddle )
.container {显示:-webkit-FLEX; -webkit-flex-direction:row;}。flexbox-1 {-webkit-flex:1; border:solid 3px red;}。flexbox-2 {-webkit-flex:2;边框:实心3px蓝色; height:200px; margin-left:10px;}
< div class = 容器 > < div class =flexbox-1> .flexbox-1< / div> < div class =flexbox-2> .flexbox-2< / div>< / div>
这是一个旧的解决方案。通过这个 Aaron使用
align-self
的新答案。这是一个更好的解决方案,不依赖于CSS怪癖。
只要flex容器本身没有高度,您可以在第一个Flex项目上设置 height:0%
。因为没有高度可以继承父级,所以任何百分比高度都会导致它崩溃。它会随着内容的增长而增长。
示例
在这个例子中,我已经移除了 -webkit
前缀。 这只是Safari所必需的,前缀可以添加上面非前缀版本。我还删除了 flex-direction:row
,因为它是默认值。 $ b
.container {display:flex;}。flexbox-1 {flex:1;身高:0%; border:solid 3px red;}。flexbox-2 {flex:2;边框:实心3px蓝色; height:200px; margin-left:10px;}
< div class = 容器 > < div class =flexbox-1> .flexbox-1< / div> < div class =flexbox-2> .flexbox-2< / div>< / div>
I have two elements inside a container, which are being side-by-side by using flex box. On the second element (.flexbox-2
), I am setting it's height in the CSS. However, then the first element (.flexbox-1
) will match the height of .flexbox-2
. How would I stop .flexbox-1
from matching the height of .flexbox-2
, and instead just retain its natural height?
Here is what I have so far (also available as a jsFiddle)
.container {
display: -webkit-flex;
-webkit-flex-direction: row;
}
.flexbox-1 {
-webkit-flex: 1;
border: solid 3px red;
}
.flexbox-2 {
-webkit-flex: 2;
border: solid 3px blue;
height: 200px;
margin-left: 10px;
}
<div class="container">
<div class="flexbox-1">.flexbox-1</div>
<div class="flexbox-2">.flexbox-2</div>
</div>
This is an old solution. My answer is superseded by this new answer by Aaron using
align-self
. That is a better solution that does not rely on a CSS quirk.
As long as the flex container has no height itself, you can set height: 0%
on the first flex item. Because it has no height to inherit from its parent, any percentage height will cause it to collapse. It will then grow with its contents.
Example
In this example I have removed the -webkit
prefix. It's only really required for Safari and the prefix can be added above the non-prefixed version. I also removed flex-direction: row
as it is the default value.
.container {
display: flex;
}
.flexbox-1 {
flex: 1;
height: 0%;
border: solid 3px red;
}
.flexbox-2 {
flex: 2;
border: solid 3px blue;
height: 200px;
margin-left: 10px;
}
<div class="container">
<div class="flexbox-1">.flexbox-1</div>
<div class="flexbox-2">.flexbox-2</div>
</div>
这篇关于防止展开Flex项目高度以匹配其他Flex项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!