html - inline-flex div 的宽度是如何决定的?

标签 html css

对于 inline-flex div,宽度取决于其子元素的宽度。这是代码,我没有设置指定宽度的父div。所以,这是由内部因素决定的。

三个子元素,一个是width:50%,其他都是width:50px,但是2最终的宽度是31.75,这是怎么来的?

    <div style="display: inline-flex;flex-wrap: nowrap;">
        <div style="width:50%;color:red">1</div>
        <div style="width:50px;color:blue">2</div>
        <div style="width:50px;color:black">3</div>
        <span>hello</span>
    </div>

enter image description here

最佳答案

以下是了解浏览器正在执行的操作的分步说明:

div div {
 outline:1px solid green
}
<p>The browser will first ignore the width:50% and use auto instead</p>
<div style="display: inline-flex;flex-wrap: nowrap;border:2px solid red">
    <div style="width:auto;color:red">1</div>
    <div style="width:50px;color:blue">2</div>
    <div style="width:50px;color:black">3</div>
    <span>hello</span>
</div>
<p>Now that we have the width of the parent, it will no more change and we resolve width:50%</p>
<div style="display: inline-flex;flex-wrap: nowrap;border:2px solid red">
    <div style="width:50%;color:red">1</div>
    <div style="width:50px;color:blue">2</div>
    <div style="width:50px;color:black">3</div>
    <span>hello</span>
</div>
<p>all the div will shrink because there is not enough space for them (50% + 50px + 50px + hello > 100%). A shrink that you can disable if you use flex-shrink:0 and you will have overflow</p>
<p>Only "hello" will not shrink because a flex item cannot shrink past its content size</p>
<div style="display: inline-flex;flex-wrap: nowrap;border:2px solid red">
    <div style="width:50%;color:red;flex-shrink:0;">1</div>
    <div style="width:50px;color:blue;flex-shrink:0;">2</div>
    <div style="width:50px;color:black;flex-shrink:0;">3</div>
    <span>hello</span>
</div>

如果您想了解计算,请了解有关收缩算法的更多详细信息:

How flexbox calculates flex-item's width if no flex-basis or width are set?

Why is a flex item limited to parent size?

要理解为什么“hello”不会缩小:

Why don't flex items shrink past content size?


您在开发工具中看到的紫色区域是收缩效果之前的宽度。您可以注意到第二个和第三个 div 等于 50px

关于html - inline-flex div 的宽度是如何决定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69375381/

相关文章:

html - 当输入类型为密码时,自动完成 ='off' 不起作用,并在其上方设置输入字段以启用自动完成

html - 如何使 Bootstrap 图像变圆?

html - 我的选择框在浏览器上的不同输出

html - 响应式电子邮件 - 媒体查询中心

css - 如何改变h :outputLabel的宽度

javascript - CSS 过渡不会在卸载前触发

html - SAS ods html 生成额外的 html 代码

javascript - 如何使用纯 Javascript 将 onclick 函数添加到动态创建的 div

javascript - 失踪案<li>

html - 背景颜色和悬停不适用于可滚动 HTML 表格中的粘性列。表格设计也不是跨浏览器一致的