Category 职业推荐

前言

今天在解决别的bug时发现了个很奇怪的东西,我的容器明明设置了flex:1为什么还会导致内容溢出,导致比我设想的flex:1尺寸来得大。

后来才知道

浏览器默认为flex容器的子元素设置了 min-width: auto;min-height: auto,这意味着子元素的最小宽度和高度不能小于其内容的宽度和高度。

这就是为什么明明是flex:1,但是为什么比预想的要大了。

正文

单单文字说明还是难以理解,来看图和代码吧

有问题的代码,父元素设置100vw,子元素设置flex:1;。

tsx

复制代码

function App() {

return (

style={{

display: "flex",

height: "100vh",

width: "100vw",

gap: "10px",

}}

>

style={{

width: "200px",

textAlign: "left",

backgroundColor: "red",

}}

>

Left

style={{

flex: 1,

textAlign: "left",

backgroundColor: "blue",

}}

>

style={{

height: "100%",

width: "100%",

overflow: "auto",

backgroundColor: "lightcyan",

}}

>

asdasd

asdasdasdasdasdsadsadasdsadasdiuoasdgiasgdfasghdiopasdyiuskafdgiuashdasgvdsadpjnasildgsaodiasoudgasiugdasyfdgasudiyfasdhoiashdgiouasgdiu

asdasd

);

}

预计是滚动条只在右边区域,总页面没有滚动条。但是实际的总页面有滚动条,右边区域没有滚动条。这就是 浏览器默认为flex容器的子元素设置了 min-width: auto;min-height: auto,这意味着子元素的最小宽度和高度不能小于其内容的宽度和高度,把右侧的内容撑大了,导致内容溢出了。

如何解决呢

设置 overflow,利用BFC

设置 min-width: 0

任意使用一种都可以,是我们预计的情况了。

修改后代码

tsx

复制代码

function App() {

return (

style={{

display: "flex",

height: "100vh",

width: "100vw",

gap: "10px",

}}

>

style={{

width: "200px",

textAlign: "left",

backgroundColor: "red",

}}

>

Left

style={{

flex: 1,

textAlign: "left",

backgroundColor: "blue",

minWidth: 0, //关键

}}

>

style={{

height: "100%",

width: "100%",

overflow: "auto",

backgroundColor: "lightcyan",

}}

>

asdasd

asdasdasdasdasdsadsadasdsadasdiuoasdgiasgdfasghdiopasdyiuskafdgiuashdasgvdsadpjnasildgsaodiasoudgasiugdasyfdgasudiyfasdhoiashdgiouasgdiu

asdasd

);

}

结语

有兴趣的可以去试试

Copyright © 2088 炎龙游戏攻略网 - 活动副本全解析 All Rights Reserved.
友情链接
top