自定义下划线以适应内容的宽度

Custom underline to fit width of contents

我正在尝试制作一条下划线,该下划线占单词长度的 50%,并在悬停的单词下方居中。

尽管选择了 a.

,但伪选择器中的宽度采用 nav 的宽度而不是悬停的 a 的宽度

当设置left属性时,nav的左边是静态的,而不是a的左边。我需要它相对于悬停的项目。

这里是相关代码:

nav a:hover::before{
    position: absolute;
    left: calc(50% - 10%);
    bottom: 0;
    width: 20%;
    height: 1px;
    background: #7b0700;
    content: "";
}

和一个 CodePen

http://codepen.io/WallyNally/pen/dXxrgj

有什么建议吗? 谢谢你。

你快到了!

遗漏部分:

nav a {
  position: relative;
}

没有它,该行定位到 DOM 中的某个元素(具有绝对位置、相对位置、固定位置,或者如果缺少正文)。

至于 50% 的宽度,我会这样做:

nav a:hover::before {
  position: absolute;
  bottom: 0;
  height: 1px;
  background: #7b0700;
  content: "";

  /* instead of width: */
  left: 25%;
  right: 25%;

}

从您的代码中分叉:http://codepen.io/anon/pen/BzXKrB