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

Safari浏览器中伪类:before背景色失效问题求助

Safari中伪类:before背景色无法正常显示

在Safari浏览器中使用:before伪类时,设置的背景色无法正常渲染,但相同代码在Chrome中显示正常。

复现代码

HTML

<div id='test'>
  <p>Test </p>
</div>

CSS

#test {
  position: relative;
  perspective: 240px;
  width: 500px;  
}

#test p {
    position: relative;
}

#test::before {
    content: '';
    position: absolute;
    top: -5px;
    bottom: -5px;
    left: 0;
    right: 0;
    line-height: 27px;
    border: 1px solid #D4E7D1;
    background: #E4F7E1;
    border-radius: 5px 5px 0 0;
    transform: rotateX(45deg); 
}

渲染差异

  • Chrome正常效果:
    Chrome正常渲染
  • Safari异常效果:
    Safari渲染异常

修复方案

在父容器#test中添加transform-style: preserve-3d开启3D空间,同时给伪元素设置z-index: -1、给文本元素设置z-index: 1明确层级关系,即可解决Safari的渲染问题:

#test {
  position: relative;
  perspective: 240px;
  width: 500px;
  transform-style: preserve-3d; /* 开启3D空间 */
}

#test p {
    position: relative;
    z-index: 1; /* 确保文本在伪元素上方 */
}

#test::before {
    content: '';
    position: absolute;
    top: -5px;
    bottom: -5px;
    left: 0;
    right: 0;
    line-height: 27px;
    border: 1px solid #D4E7D1;
    background: #E4F7E1;
    border-radius: 5px 5px 0 0;
    transform: rotateX(45deg);
    z-index: -1; /* 将伪元素置于文本下方 */
}

原因说明

Safari对3D变换的渲染逻辑与Chrome不同,需要显式声明transform-style: preserve-3d来维持父元素与子元素(包括伪元素)的3D空间关系;同时通过z-index明确层级,避免伪元素被内容遮挡或背景色不渲染的问题。

内容的提问来源于stack exchange,提问作者Deepesh Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:15:31