You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用flex: 0 0 auto;在Edge/Safari出现1px间隙,如何修复?

问题:Edge和Safari中Flex容器子元素间出现1px黑色间隙

在CSS中使用flex: 0 0 auto;属性后,仅在Edge和Safari浏览器中,类名为.scrollWrapper的flex容器的子div元素之间出现了1px黑色间隙,其他浏览器无此问题。

相关代码如下:

CSS代码

body {
    overflow: hidden;
    position: relative;
    height: 100vh;
    width: 100vw;
    background-color: black;
}

.scrollWrapper {
    position: relative;
    overflow-x: hidden;
    overflow-y: scroll;
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
}

.scrollWrapper > * {
    background-color: white;
    height: 10%;
    width: 100%;
    flex: 0 0 auto;
}

HTML代码

<div class="scrollWrapper">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
修复方案
  • 方案1:用flex属性直接控制高度
    把子元素的height:10%替换为flex: 0 0 10%,同时移除单独的flex:0 0 auto,让flex属性直接管理基准尺寸,避免浏览器计算偏差:

    .scrollWrapper > * {
        background-color: white;
        width: 100%;
        flex: 0 0 10%;
    }
    
  • 方案2:用负margin抵消间隙
    给子元素设置margin-bottom: -1px,直接覆盖间隙;可选移除最后一个元素的负margin,避免底部溢出:

    .scrollWrapper > * {
        background-color: white;
        height: 10%;
        width: 100%;
        flex: 0 0 auto;
        margin-bottom: -1px;
    }
    /* 可选:移除最后一个元素的负margin */
    .scrollWrapper > *:last-child {
        margin-bottom: 0;
    }
    
  • 方案3:触发硬件加速修正渲染
    给子元素添加transform: translateZ(0)触发GPU渲染,修正浏览器的像素计算误差:

    .scrollWrapper > * {
        background-color: white;
        height: 10%;
        width: 100%;
        flex: 0 0 auto;
        transform: translateZ(0);
    }
    
  • 方案4:用calc()微调高度
    把height:10%改成height: calc(10% + 1px),让子元素高度稍微超出一点,覆盖间隙:

    .scrollWrapper > * {
        background-color: white;
        height: calc(10% + 1px);
        width: 100%;
        flex: 0 0 auto;
    }
    

内容的提问来源于stack exchange,提问作者Dan Wiedenhoever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:17:03