前言
今天在解决别的bug时发现了个很奇怪的东西,我的容器明明设置了flex:1为什么还会导致内容溢出,导致比我设想的flex:1尺寸来得大。
后来才知道
浏览器默认为flex容器的子元素设置了 min-width: auto;min-height: auto,这意味着子元素的最小宽度和高度不能小于其内容的宽度和高度。
这就是为什么明明是flex:1,但是为什么比预想的要大了。
正文
单单文字说明还是难以理解,来看图和代码吧
有问题的代码,父元素设置100vw,子元素设置flex:1;。
1function App() { 2 return ( 3 <div 4 style={{ 5 display: "flex", 6 height: "100vh", 7 width: "100vw", 8 gap: "10px", 9 }} 10 > 11 <div 12 style={{ 13 width: "200px", 14 textAlign: "left", 15 backgroundColor: "red", 16 }} 17 > 18 Left 19 </div> 20 <div 21 style={{ 22 flex: 1, 23 textAlign: "left", 24 backgroundColor: "blue", 25 }} 26 > 27 <section 28 style={{ 29 height: "100%", 30 width: "100%", 31 overflow: "auto", 32 backgroundColor: "lightcyan", 33 }} 34 > 35 <div> 36 <div>asdasd</div> 37 <div> 38 asdasdasdasdasdsadsadasdsadasdiuoasdgiasgdfasghdiopasdyiuskafdgiuashdasgvdsadpjnasildgsaodiasoudgasiugdasyfdgasudiyfasdhoiashdgiouasgdiu 39 </div> 40 <div>asdasd</div> 41 </div> 42 </section> 43 </div> 44 </div> 45 ); 46} 47
预计是滚动条只在右边区域,总页面没有滚动条。但是实际的总页面有滚动条,右边区域没有滚动条。这就是浏览器默认为flex容器的子元素设置了 min-width: auto;min-height: auto,这意味着子元素的最小宽度和高度不能小于其内容的宽度和高度,把右侧的内容撑大了,导致内容溢出了。
如何解决呢
- 设置 overflow,利用BFC
- 设置 min-width: 0
任意使用一种都可以,是我们预计的情况了。
修改后代码
1function App() { 2 return ( 3 <div 4 style={{ 5 display: "flex", 6 height: "100vh", 7 width: "100vw", 8 gap: "10px", 9 }} 10 > 11 <div 12 style={{ 13 width: "200px", 14 textAlign: "left", 15 backgroundColor: "red", 16 }} 17 > 18 Left 19 </div> 20 <div 21 style={{ 22 flex: 1, 23 textAlign: "left", 24 backgroundColor: "blue", 25 minWidth: 0, //关键 26 }} 27 > 28 <section 29 style={{ 30 height: "100%", 31 width: "100%", 32 overflow: "auto", 33 backgroundColor: "lightcyan", 34 }} 35 > 36 <div> 37 <div>asdasd</div> 38 <div> 39 asdasdasdasdasdsadsadasdsadasdiuoasdgiasgdfasghdiopasdyiuskafdgiuashdasgvdsadpjnasildgsaodiasoudgasiugdasyfdgasudiyfasdhoiashdgiouasgdiu 40 </div> 41 <div>asdasd</div> 42 </div> 43 </section> 44 </div> 45 </div> 46 ); 47} 48
结语
有兴趣的可以去试试
《解密Flex布局:为什么flex:1仍会导致内容溢出》 是转载文章,点击查看原文。