【问题标题】:Why are ::before and ::after pseudo-elements detected but not shown in Chrome?为什么检测到 ::before 和 ::after 伪元素但未在 Chrome 中显示?
【发布时间】:2021-06-02 10:46:40
【问题描述】:

我想设计一个 1px 线的水平分隔线。在该行的中间,有一个 svg。所以我为此使用 hr:before 和 hr:after :

<hr class="linha" />

SCSS:

hr.linha {
    border: 0;
    border-top: 1px solid $primary;
    height: 0;
    margin: 4rem auto 4rem;
    text-align: center;
    width: 30%;

    &::before {
        content: "";
        background: white url("/img/logo-e.svg") no-repeat center;
        background-size: 20px 20px;
        margin: 0 auto;
        padding: 20px;
        position: relative;
        top: -15px;
        left: 0;
        right: 0;
    }

    &::after {
        content: " ";
        clear: both;
    }
}

Firefox 和 Safari 会按预期显示:一个水平的,中间有一个图像。 Chrome 只显示一条不间断的水平线。 ::before 伪元素存在,但屏幕上没有显示任何内容。

在 Chrome 的 Inspector 上,“computed styles”表明它正在计算图像并且图像可以看到,这意味着 url 路径是正确的。

我已经尝试过的:

  • 使用 :before 或 ::before
  • 仅使用 :before
  • 使用内容:url("logo.svg") 代替背景:url("logo.svg")
  • 使用内容:“一些文本”而不​​是背景:url(“logo.svg”)
  • 应用 display: inline-block 或 display: block

为什么 Chrome 不显示 :before 伪元素?

【问题讨论】:

  • 您是否尝试过添加宽度和高度?
  • 哦,是的,忘记提了。是的,我试过设置宽度和高度。

标签: html css sass


【解决方案1】:

如果使用相对位置,chrome会在之前使用自动宽度。如果使用绝对位置,则logo会正确显示。

hr.linha:before {
    position: absolute;
}

【讨论】:

  • 这是正确答案。定位它变得稍微困难​​一些,但 Chrome 现在显示了它。谢谢!供将来参考:定位对象时,请始终检查计算的样式。它显示宽度设置为自动,我没有注意到。
猜你喜欢
  • 2015-09-12
  • 2016-05-24
  • 1970-01-01
  • 2013-06-08
  • 2013-06-15
  • 2014-02-08
  • 2020-09-20
  • 2021-12-27
  • 2011-04-02
相关资源
最近更新 更多