添加背景图像到一串动态文本的末尾,在文本后面

Add a background image to the end of a string of dynamic text, behind the text

我需要在我的 h1 文本后面(或前面 - 这无关紧要)放置一张图片,并将其放置在文本末尾的右侧,例如这个:

我似乎无法让背景图像显示在文本之上或之后。我错过了什么?

h1 {
  text-align: center;
}

h1:after {
  content: "";
  background: url("https://static1.squarespace.com/static/50f111c8e4b02b3b2218af91/t/5d9fa26b176671739c726240/1570742891482/CRMC-2020-Measure-h1-1a.png") no-repeat;
  background-position: -85px 12px;
  background-size: 32%;
  width: 400px;
  height: 50px;
  position: absolute;
}
<h1>Dynamic Headline</h1>

使用 :after,我无法让图像显示在文本的后面或上面。

为了移动背景以显示在文本之上,而不是您正在寻找的 background-position margin-left。但是请注意,您不能将 margin-bottom 应用于绝对定位的元素,因此您仍然需要使用 background-position 来调整垂直偏移。在以下示例中,我已将其更改为 4px

h1 {
  text-align: center;
}

h1:after {
  content: "";
  background: url("https://static1.squarespace.com/static/50f111c8e4b02b3b2218af91/t/5d9fa26b176671739c726240/1570742891482/CRMC-2020-Measure-h1-1a.png") no-repeat;
  background-size: 32%;
  width: 400px;
  height: 50px;
  position: absolute;
  margin-left: -85px;
  background-position: 0 4px;
}
<h1>Dynamic Headline</h1>

我会用一个 span 包裹文本,它有左右填充,然后将图像作为 span 的背景,并将其放在右边:

h1 {
  text-align: center;
}

h1 span {
  padding: 0 1.3em;
  background: url("https://static1.squarespace.com/static/50f111c8e4b02b3b2218af91/t/5d9fa26b176671739c726240/1570742891482/CRMC-2020-Measure-h1-1a.png") right top no-repeat;
  background-size: contain;
}
<h1>
  <span>Dynamic Headline</span>
</h1>

同样的想法没有 span,但由于 width: content-fit 而不受 IE/Edge 支持。

h1 {
  width: fit-content;
  margin: 0 auto;
  padding: 0 1.3em;
  background: url("https://static1.squarespace.com/static/50f111c8e4b02b3b2218af91/t/5d9fa26b176671739c726240/1570742891482/CRMC-2020-Measure-h1-1a.png") right top no-repeat;
  background-size: contain;
}
<h1>Dynamic Headline</h1>