[英]How to calculate the actual width of child elements of a flexbox container?
I have such html and css code.我有这样的 html 和 css 代码。 I have two questions:我有两个问题:
widthOfParent
- widthOfLeft
.它只需要widthOfParent
- widthOfLeft
。 I suppose it should somehow overflow and reach 100vw.我想它应该以某种方式溢出并达到100vw。 <div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
* {
margin: 0;
padding: 0;
}
.container {
height: 300px;
/* your code here */
display: flex;
justify-content: start;
}
.left {
background-color: #f44336;
height: 100%;
width: 25%;
min-width: 100px;
}
.right {
background-color: #2973af;
height: 100%;
width: 100vw;
}
codesanbox: https://codesandbox.io/s/admiring-darkness-cu99x?file=/src/styles.css:0-293代码框: https://codesandbox.io/s/admiring-darkness-cu99x?file=/src/styles.css:0-293
.container { height: 300px; width: 600px; /* added fixed width for testing */ display: flex; justify-content: start; }.left { background-color: #f44336; min-width: 100px; flex: 1; /* 1/4 ratio within the parent element, as the other flex item in the parent is "flex: 3;" */ }.right { background-color: #2973af; flex: 3; /* 3/4 ratio within the parent element, as the other flex item in the parent is "flex: 1;" */ }
CSS flex Property https://www.w3schools.com/cssref/css3_pr_flex.asp CSS flex 属性https://www.w3schools.com/cssref/css3_pr_flex.asp
You are facing the shrink effect.你正面临收缩效应。 In all the cases the total width 100vw + 25%
is bigger than 100%
so both items will shrink equally.在所有情况下,总宽度100vw + 25%
大于100%
,因此两个项目将同等收缩。
Since your container is also full width, the overflow will always be equal to 25%
or 25vw
.由于您的容器也是全宽的,因此溢出将始终等于25%
或25vw
。 Both element have the default shrink value 1
so we have a sum equal to 125vw
.这两个元素都有默认的收缩值1
所以我们的总和等于125vw
。
The first element width will be equal to: 25vw - (25vw * 25vw/125vw) = 20vw
and the width of the second item will be: 100vw - (25vw * 100vw/125vw) = 80vw
第一个元素的宽度将等于: 25vw - (25vw * 25vw/125vw) = 20vw
,第二个元素的宽度将是: 100vw - (25vw * 100vw/125vw) = 80vw
You can logically see that the total is 100vw
( 20vw + 80vw
) and when the screen width is equal to 600px
, 20vw
is equal 120px
.你可以从逻辑上看到总数是100vw
( 20vw + 80vw
),当屏幕宽度等于600px
时, 20vw
等于120px
。
To avoid this, disable the shrink effect on the first item by setting flex-shrink:0
为避免这种情况,请通过设置flex-shrink:0
禁用第一项的收缩效果
* { margin: 0; padding: 0; }.container { height: 300px; /* your code here */ display: flex; }.left { background-color: #f44336; width: 25%; min-width: 100px; flex-shrink:0; }.right { background-color: #2973af; width: 100vw; }
<div class="container"> <div class="left"></div> <div class="right"></div> </div>
Related: Why is a flex item limited to parent size?相关:为什么弹性项目仅限于父尺寸?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.