css - 为什么 flexbox 不会增长到它的文本?

标签 css flexbox flex-grow

我需要 .child-1-2 来扩展到它的文本,但是文本溢出了。当我将 .child-1-1flex-basis50px 更改为 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-basisflex-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 元素的宽度按以下顺序确定:

  1. 内容
  2. 宽度
  3. 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/

相关文章:

html - Safari 6 (iOS 6) flex 布局不换行元素

html - CSS3 flex : flex-grow + justify-content?

css - 为什么第一个 div 中的 flex-grow 会影响第三个 div?

html - 菜单项在悬停时移动且无法居中

php - 迁移 PHP 5.2 网站

html - 为什么aspectraio 不适用于Flexbox 子项?

html - 了解 flex 增长

javascript - 当宽度 < XXX 像素时禁用图例 charts.js

javascript - 菜单栏事件类Smarty模板

javascript - 当我在 img 标签周围添加链接时,将元素居中对齐在 img 元素上不起作用