使用 ::before 和 z-index 偏移 Header 突出显示 -- 仅 CSS

Offset Header Highlight with ::before and z-index -- CSS only

这是我在 Stack 上的第一个问题,所以如果我违反约定,请 correct/inform 以便我下次可以更好地查询此资源!

我正在尝试使用覆盖 header 文本下半部分的偏移突出显示来设置 header 元素的样式,如下所示:

see the blue highlight on the "bottleneck" -- http://jessecha.se/work/blueapron.html

作者用一个::before元素和-1的z-index实现了它。无论我使用 ::before 还是 ::after,我都遇到了问题:

1) 使 pseudo-element 对齐到 header 元素的底部

2) 在不指定像素宽度的情况下使 pseudo-element 与 header 的宽度相同。将 header 设置为显示为 table 会更好吗?

代码如下:

h2::after {
  content: "";
  position: absolute;
  width: 400px;
  background: orange;
  left: 0;
  height: .6em;
  z-index: -1;
}
</head>

<body>
  <article>
    <h2 style="width: 500px">
      Highlighting Header Styles
    </h2>
  </article>
</body>

</html>

h2元素需要position: relative(position:absolute元素需要 容器元素为 position:relative 或绝对)并且 h2 元素需要 是 display: inline-block(因为宽度)和 :after 元素添加 width: 100%

h2{
  position: relative;
  display:inline-block;
}
h2::after {
  content: "";
  position: absolute;
  width: 100%;
  background: orange;
  left: 0;
  bottom: 0;
  height: .6em;
  z-index: -1;
}
</head>

<body>
  <article>
    <h2>
      Highlighting Header Styles
    </h2>
  </article>
</body>

</html>