简体   繁体   中英

How the width of a inline-flex div is decided?

for an inline-flex div, the width is depending on its children elements' width. Here is the code, I don't set the parent div with specified width. So, it is decieded by inside elements.

For the three children elements, one is with width:50% , others are width:50px , but the final width for 2 is 31.75, how does it come?

    <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>

在此处输入图像描述

Here is a step by step illustration to understand what the browser is doing:

 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>

For more detail about the shrink algorithm if you want to understand the calculation:

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

Why is a flex item limited to parent size?

To understand why "hello" will not shrink:

Why don't flex items shrink past content size?


The purple area you see in the dev tools is the width before the shrink effect. You can notice it's equal to 50px for the 2nd and 3rd div

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM