首页 > 解决方案 > 如何将margin-top添加到伪元素

问题描述

我试图在包含 css 伪元素的标题中添加边距顶部。

当尝试添加我的边距顶部时,伪元素(文本上方的行)嵌套在我的边距内。我怎样才能在它上面添加边距。

CSS

.line-top{
  font-size: 32px;
  font-weight: 200;
  padding: 30px 0;
  letter-spacing: 2px;
  margin-top:5rem;

  &::before{
    position: absolute;
    display: inline-block;
    content: '';
    background:
     linear-gradient(
       to left,
       $orange 0,
       $orange 50.00%,
       $teal 50.00%,
       $teal  )no-repeat;
    height: 4px;
    width: 190px;
    top: 15px;
  }
}

HTML

<h3 class="line-top">ME Text Title </h3>

图片

显示嵌套元素的图像

标签: htmlcssmarginpseudo-element

解决方案


您正在将::before伪元素设置为绝对位置,但是您没有在.line-top. 因此,它将使用默认值(静态)。

您需要改用相对定位。

.line-top {
    position: relative;
    ...

文档:https ://developer.mozilla.org/en-US/docs/Web/CSS/position


推荐阅读