解密Flex布局:为什么flex:1仍会导致内容溢出

前言

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

后来才知道

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

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

正文

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

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

tsx 复制代码
function App() {
  return (
    <div
      style={{
        display: "flex",
        height: "100vh",
        width: "100vw",
        gap: "10px",
      }}
    >
      <div
        style={{
          width: "200px",
          textAlign: "left",
          backgroundColor: "red",
        }}
      >
        Left
      </div>
      <div
        style={{
          flex: 1,
          textAlign: "left",
          backgroundColor: "blue",
        }}
      >
        <section
          style={{
            height: "100%",
            width: "100%",
            overflow: "auto",
            backgroundColor: "lightcyan",
          }}
        >
          <div>
            <div>asdasd</div>
            <div>
              asdasdasdasdasdsadsadasdsadasdiuoasdgiasgdfasghdiopasdyiuskafdgiuashdasgvdsadpjnasildgsaodiasoudgasiugdasyfdgasudiyfasdhoiashdgiouasgdiu
            </div>
            <div>asdasd</div>
          </div>
        </section>
      </div>
    </div>
  );
}

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

如何解决呢

  1. 设置 overflow,利用BFC
  2. 设置 min-width: 0

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

修改后代码

tsx 复制代码
function App() {
  return (
    <div
      style={{
        display: "flex",
        height: "100vh",
        width: "100vw",
        gap: "10px",
      }}
    >
      <div
        style={{
          width: "200px",
          textAlign: "left",
          backgroundColor: "red",
        }}
      >
        Left
      </div>
      <div
        style={{
          flex: 1,
          textAlign: "left",
          backgroundColor: "blue",
          minWidth: 0, //关键
        }}
      >
        <section
          style={{
            height: "100%",
            width: "100%",
            overflow: "auto",
            backgroundColor: "lightcyan",
          }}
        >
          <div>
            <div>asdasd</div>
            <div>
              asdasdasdasdasdsadsadasdsadasdiuoasdgiasgdfasghdiopasdyiuskafdgiuashdasgvdsadpjnasildgsaodiasoudgasiugdasyfdgasudiyfasdhoiashdgiouasgdiu
            </div>
            <div>asdasd</div>
          </div>
        </section>
      </div>
    </div>
  );
}

结语

有兴趣的可以去试试

相关推荐
疯华整猫1 天前
被杀掉之后:我把 Android 的「唤起 + 常驻」重做了一遍
前端·面试·架构
IT_陈寒1 天前
Java开发实战:从入门到精通
前端·人工智能·后端
风骏时光牛马1 天前
生成一个AI转岗经历标题,只需要一个标题,不需要其他的任何文本。
前端
Csvn1 天前
Monorepo
前端
Csvn1 天前
流水线
前端
Csvn1 天前
微前端架构
前端
Linux-lucky1 天前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
风骏时光牛马2 天前
生成一个移动端标题,只需要一个标题,不需要其他的任何文本。
前端
IT_陈寒2 天前
Redis雪崩把我坑惨了,这是5年经验的教训
前端·人工智能·后端
SameX2 天前
HarmonyOS ArkUI List 的侧滑删除 用 ListItem 的 swipeAction + endIcon 的做法
前端