【问题标题】:CSS - bottom border using :after pseudo-element that's the length of text [duplicate]CSS - 使用 :after 伪元素的底部边框,这是文本的长度 [重复]
【发布时间】:2020-03-27 06:38:01
【问题描述】:

我有一个<h3>,我需要使用::after 伪元素对其进行样式设置,使其后面包含一个红色底边。

目标: 红底边框应该只显示文本的长度。

结果: 我现在最接近的,边框跨越父宽度。

<h3><span class="headingLine">Lorem Ipsum Dolor Sit Amet</span></h3>

span.headingLine:after{
  position: absolute;
  content: '';
  border-bottom: 7px solid red;
  z-index: -1;
  left: 0;
  width: 100%; /* If I remove the width 100%, the red doesn't show */
  bottom: 15px;
  display: inline-block;
}

如何调整标记/CSS 以使红色边框仅跨越文本的宽度?

可能存在多行文本(浏览器窗口小/标题较长)

【问题讨论】:

  • 位置:相对于跨度(和内联块)
  • 它已经是内联块了。相对定位将红色边框推到文本下方,它仍然跨越父级的整个宽度。
  • 内联块到跨度,而不是 after 伪元素,不,它不是位置:如果我考虑你所显示的数字,除非你通过发布你的整个代码证明我错了
  • "到 span,而不是 after 伪"。啊哈。知道了。您的解决方案适用于 1 行文本。 2 或更多,而红线只出现在最底线。 (见我问题的最后一部分)

标签: html css css-selectors pseudo-class


【解决方案1】:

您的方法过于复杂,只需使用渐变背景即可:

h3 {
  border: solid 1px
}

span {
  background: linear-gradient(0deg, red 6px, transparent 7px) 0 1.1em
}
<h3><span class="headingLine">Lorem Ipsum Dolor Sit Amet</span></h3>
<h3><span class="headingLine">Lorem Ipsum Dolor Sit Amet Dolor Sit Amet Dolor Sit Amet Dolor Sit Amet Dolor Sit Amet Dolor Sit Amet</span></h3>

【讨论】:

  • 非常干净!我不得不稍微调整一下值,但它非常接近。有什么办法可以推高那条红线,使它更像是一个背景元素? (在我发布的屏幕截图中,红线从小写 p 的下降部分开始)
  • @Joe,是的,它是可调节的。查看背景位置编号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 2017-10-31
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
  • 2021-11-13
相关资源
最近更新 更多