如何在标题的一部分下划线(例如前 40px)?

How to underline part of a heading (first 40px for instance)?

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

使用 pseudo-element:

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

您可以使用 :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;
}
<h1>This is a header, partly underlined</h1>

您可以添加一个包含几个带下划线的不间断空格的伪元素。这样你就得到了真正的下划线而不是边框​​。但是它仍然会跨越 "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>