如何居中和改变下划线的长度?

How to center and change the length of underline?

我有一些文字需要在单词的中间部分下加下划线。

我创建了 fiddle and I want the underline should be centered as shown in this image

我在 fiddle 中包含的 CSS 代码是:

.footer p
{
  width: 50%;
  border-bottom: 1px solid #f51c40;
}

这可以通过多种方式完成,需要您提供更多信息...

这是我的想法,非常简单

<div class="footer">
    <p>Add<u>ition</u>al</p>
</div>

另一种选择包括使用 .footer p :before and/or :after 伪元素...

您可以使用 ::after 伪元素。如果你不知道伪元素是什么,我推荐你 learn about them here 因为它是 CSS 的一个非常重要的部分,你会经常使用。 ::after 伪元素可以在某个元素之后添加内容。

您可以在 p 元素之后创建边框,例如:

.footer p::after {content:""; height: 1px; width: 50px; background-color: red;}

它应该像您需要的那样工作

footer p
{
  width: 50%;
}

footer p:after {
  content: '';
  border-bottom: 2px #000 solid;
  position: absolute;
  top:40px;
  left: 30px;
  width:100px;
}

https://jsfiddle.net/74zgg81d/1/

您可以使用带有 left: 50%; transform: translate(-50%); 的绝对定位伪元素,使其相对于内容自动水平居中。

.footer p {
  display: inline-block;
  position: relative;
}

.footer p:after {
  content: "";
  height: 1px;
  width: 50%;
  background-color: red;
  position: absolute;
  bottom: -.5em;
  left: 50%;
  transform: translate(-50%);
}
<div class="footer">
  <p>ADDITIONAL INFO</p>
</div>

最好的方法是使用 css 伪元素 ::after。您还必须将 display: inline-blockposition: relative 设置为 p 元素。

请看下面的片段:

.footer p {
  display: inline-block;
  position: relative;
}

.footer p::after {
  content: "";
  width: 60px;
  height: 3px;
  background: black;
  position: absolute;
  left: 0;
  right: 0;
  margin: auto;
  bottom: -3px;
}
<div class="footer">
  <p>ADDITIONAL INFO</p>
</div>