我需要 .child-1-2
来扩展到它的文本,但是文本溢出了。当我将 .child-1-1
的 flex-basis
从 50px
更改为 auto
时,它似乎可以工作.为什么会这样?
.parent-1 {
display: flex;
}
.child-1 {
display: flex;
flex: 0 0 auto;
background: #4c72af;
}
.child-1-1 {
display: flex;
flex: 0 0 50px;
}
.child-1-2 {
display: flex;
flex: 1 0 auto;
}
.child-2 {
display: flex;
flex: 1 0 auto;
background: #f7ed7e;
}
<div class="parent-1">
<div class="child-1">
<div class="child-1-1">C1</div>
<div class="child-1-2">Some text</div>
</div>
<div class="child-2">
<div class="child-2-1">Another text</div>
</div>
</div>
最佳答案
为了理解所描述的行为发生的原因,我们应该知道 flex-basis
和 flex-grow
是如何工作的,以及 flex 元素的宽度是多少计算。
flex 增长
来自 flex-grow is weird. Or is it?
If we apply display: flex; to the parent element and don't change anything else, the child elements will be stacked horizontally, no matter what. If there isn't enough space, they will shrink in size. If on the other hand there is more than enough space, they won't grow, because Flexbox wants us to define how much they should grow. So rather than telling the browser how wide an element should be, flex-grow determines how the remaining space is distributed amongst the flex items and how big the share is each item receives.
flex 基础
flex 元素的宽度按以下顺序确定:
- 内容
- 宽度
- flex-basis(受最大|最小宽度限制)
来自 The Difference Between Width and Flex Basis
If no flex-basis is specified, then the flex-basis falls back to the item’s width property.
If no width is specified, then the flex-basis falls back to the computed width of the item’s contents.
关于css - 为什么 flexbox 不会增长到它的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594105/