V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yodhcn
V2EX  ›  程序员

哪位前端老哥能解释一下,为什么容器设置 overflow-y 也能防止元素*宽度*溢出容器?

  •  
  •   yodhcn ·
    yodhcn · 15 小时 34 分钟前 · 908 次点击

    设计的布局很简单:左侧 nav ,右侧 main ; mian 容器中放一个 swiper 轮播组件,宽度默认充满容器。但是

    [ codesandbox ] https://codesandbox.io/p/devbox/gzlqqh

    • 为什么 swiper 在未设置宽度情况下,宽度无限大并超出容器? Swiper 宽度溢出 main 容器
    • 为什么容器设置 overflow-y 也能防止元素宽度溢出容器? Swiper 宽度充满容器

    初学 CSS 的时候就听说设置 overflow 能治一些疑难杂症,问题是解决了,但想不通是怎么解决的,哪位有经验的前端老哥能解释一下?

    7 条回复    2024-09-19 17:04:13 +08:00
    yongjing
        1
    yongjing  
       15 小时 24 分钟前
    设置 overflow 能治一些疑难杂症 这个应该是说 BFC
    https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_display/Block_formatting_context
    old9
        2
    old9  
       14 小时 52 分钟前   ❤️ 1
    第一个问题,宽度并不是无限大,是被这个 swiper 组件计算并指定的。看起来很大应该是这个组件的计算 bug 。
    第二个问题,因为标准就这么定义的

    CSS spec: https://www.w3.org/TR/css-overflow-3/
    The visible/clip values of overflow compute to auto/hidden (respectively) if one of overflow-x or overflow-y is neither visible nor clip.

    MDN 解读: https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-x
    If overflow-y is hidden, scroll, or auto, and the overflow-x property is visible (default), the value will be implicitly computed as auto.
    shintendo
        3
    shintendo  
       14 小时 27 分钟前   ❤️ 1
    简单来说,overflow 的默认值是两个方向都 visible ,但同时又禁止单个方向 visible ,所以如果你改了一个方向,就会让另一个方向变成 auto.

    不要试图用理性去挑战不可名状的 CSS Spec ,你会陷入疯狂的。
    kongkongye
        4
    kongkongye  
       14 小时 1 分钟前
    @shintendo 的确,我一直觉得 css 很复杂,有些样式怎么都调不好
    Yaavi
        5
    Yaavi  
       13 小时 51 分钟前   ❤️ 1
    看了代码,俺来解释下:设置了 overflow-y 这时候 overflow-x 被隐式改为了 auto ,而 overflow 值不为 visible 或 clip 的块级元素会触发重新创建新的 BFC ,理解成 重新创建了一个 独立的小盒子 就行,这个时候这个 独立的小盒子 的宽度会由父元素的宽度决定,所以出现了描述中的效果。
    yodhcn
        6
    yodhcn  
    OP
       13 小时 45 分钟前
    @shintendo #3 但是设置 overflow-x-hidden 、overflow-x-auto 、overflow-y-hidden 、overflow-y-auto 任意一个都能解决这个问题。我也怀疑是 swiperjs 组件计算宽度的 bug ,但我看不懂源码,不清除组件宽度计算的具体逻辑
    kile
        7
    kile  
       13 小时 40 分钟前   ❤️ 1
    切记,css 是背的不是去理解的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1102 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 22:44 · PVG 06:44 · LAX 15:44 · JFK 18:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.