【问题标题】:How to underline part of a heading (first 40px for instance)?如何在标题的一部分下划线(例如前 40px)?
【发布时间】:2016-08-20 00:25:39
【问题描述】:

是否可以在简单的 CSS 中仅将标题部分下划线,特别是左侧的前 50 像素?

【问题讨论】:

  • 有什么理由不使用虚拟元素甚至是固定宽度的样式化 hr 标签?

标签: css underline


【解决方案1】:

您可以添加一个伪元素,其中包含几个带下划线的不间断空格。这样你得到一个真正的下划线而不是边框​​。但是它仍然会跨越诸如“g”之类的字母。

h1::before {
  content:'\a0\a0\a0\a0\a0\a0\a0\a0';
  display:block;
  position:absolute;
  text-decoration:underline;
  width:50px;
  overflow:hidden;
}
<h1>Headline</h1>
<h1>Another Headline</h1>

【讨论】:

    【解决方案2】:

    您可以使用:before 伪元素并为其添加边框。

    h1 {
      position: relative;
      line-height: 1.2em;
    }
    h1:before {
      position: absolute;
      left: 0;
      top: 1.2em;
      height: 0;
      width: 50px;
      content: '';
      border-top: 1px solid red;
    }
    &lt;h1&gt;This is a header, partly underlined&lt;/h1&gt;

    【讨论】:

      【解决方案3】:

      使用pseudo-element

      h1 {
        position: relative;
      }
      h1::before {
        content: '';
        position: absolute;
        bottom: 0; left: 0;
        width: 50px;
        height: 2px;
        background-color: green;
      }
      &lt;h1&gt;foobar&lt;/h1&gt;

      【讨论】:

      • 比我的答案快 10 秒,甚至略好。 +1
      • 是的,使用的样式较少,但是 - 类似的结果 :) 如果 OP 想要“更漂亮的效果”,您可以使用 border-style 进行操作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      相关资源
      最近更新 更多