我想找一种替代方法,能够实现与一条线或随文本呈现的SVG相同的视觉效果

前端开发 2026-07-10

我在找另一种实现相同效果的方法,但不使用白色背景来遮挡SVG下方的那条线。否则,当背景是具有不同颜色的图片时——它会让白色方块格外突出,这不是我想要的效果。

要求:

  • 这条线必须始终紧跟在文本之后。
  • 这条线和SVG必须始终放在一起,且必须始终紧随文本的最后一个单词之后。
  • 如果文本换成两行,换行处和SVG应该在第二行跟随,以此类推。

如果没有办法仅用CSS实现,也可以使用一点点JavaScript。

.title {
  overflow: hidden;
  position: relative;
  font-weight: bold;
  padding-right: 62px;
}

.title:after {
  content: '';
  display: inline-block;
  height: 3px;
  translate: 12px calc(50% - 0.5lh + 1.5px);
  vertical-align: bottom;
  border-image: conic-gradient(#f00 0 0) 0 1/0 100vw 0 0/0 100vw 0 0;
}

.svg {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 42px;
  height: 1lh;
  transform: translateY(calc(50% - 0.5lh));
  background-color: #fff; /* I wan't remove this line to maintain transparency. */
  z-index: 1;
}
<h1 class="title">
  How can you ensure that the line follows the text in all circumstances?
  <svg class="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#e74c3c">
    <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
  </svg>
</h1>

解决方案

对HTML做一点点改动(把文本包裹在一个 span 标签中),对 span 做一点点CSS,使其成为一个带有overflow hidden的块以隐藏任何溢出,并把 :after 移动到span内。你的SVG已经定位好了,所以不需要再做额外改动,标题的内边距也许再调小一点,这是我的看法。

body {background: lightblue}

.title {
  overflow: hidden;
  position: relative;
  font-weight: bold;
  padding-right: 62px;
}

.title span:after {
  content: '';
  display: inline-block;
  height: 3px;
  translate: 12px calc(50% - 0.5lh + 1.5px);
  vertical-align: bottom;
  border-image: conic-gradient(#f00 0 0) 0 1/0 100vw 0 0/0 100vw 0 0;
}

span {
  display: block;
  overflow: hidden;
}

.svg {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 42px;
  height: 1lh;
  transform: translateY(calc(50% - 0.5lh));
  z-index: 1;
}
<h1 class="title">
  <span>How can you ensure that the line follows the text in all circumstances?</span>
  <svg class="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#e74c3c">
    <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
  </svg>
</h1>

Another length

<h1 class="title">
  <span>How can you ensure that the line follows the text in all circumstances? Some more text.</span>
  <svg class="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#e74c3c">
    <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
  </svg>
</h1>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章