为什么position: sticky属性在Safari浏览器中无法正常生效?
你遇到的是Safari浏览器对横向滚动场景下position: sticky的独有兼容问题,Chrome和Firefox会自动识别滚动容器作为sticky的定位上下文,Safari需要显式配置相关属性才能生效。
具体修改点
- 给滚动容器
.right-child添加position: relative,明确作为sticky元素的定位上下文 - 给sticky定位的
.first-right-child、.second-right-child添加z-index: 1,避免滚动时被后续内容覆盖 - 添加
transform: translate3d(0, 0, 0)触发Safari的GPU渲染,减少渲染异常概率 - 给sticky元素添加背景色,避免滚动时下方内容透显,影响视觉效果
修改后完整代码
CSS
.parent { display: flex; width: 100%; height: 100%; } .left-child { width: 25%; border-right: 1px solid; } .right-child { width: 75%; overflow: auto; /* 明确作为sticky元素的定位上下文 */ position: relative; } .first-right-child { position: sticky; left: 0; z-index: 1; transform: translate3d(0, 0, 0); background: #fff; } .second-right-child { position: sticky; left: 0; z-index: 1; transform: translate3d(0, 0, 0); background: #fff; } .overflowing-container { width: 1500px; }
HTML
原有HTML代码无需调整即可生效。
兜底兼容方案
如果上述修改后仍有异常,可以给滚动容器内部添加一层宽度容器,强制所有子元素的总宽度和溢出内容对齐,调整如下:
调整后的HTML
<div class="parent"> <div class="left-child"> LEFT CHILD </div> <div class="right-child"> <!-- 新增内层宽度容器 --> <div class="right-inner-wrapper"> <div class="first-right-child"> FIRST RIGHT CHILD </div> <div class="second-right-child"> SECOND RIGHT CHILD </div> <div class="third-right-child"> THIRD RIGHT CHILD <div class="overflowing-container"> Overflowing </div> </div> </div> </div> </div>
新增CSS
.right-inner-wrapper { width: fit-content; min-width: 100%; }
内容的提问来源于stack exchange,提问作者Kiran Shinde
相关产品推荐
相关产品推荐

