对于 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>
最佳答案
以下是了解浏览器正在执行的操作的分步说明:
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/