Naltroc Naltroc - 3 months ago 16
CSS Question

Custom underline to fit width of contents

I am trying to make an underline that is 50% the length of the word and centered under the word being hovered.

The width in the pseudo selector takes the width of the

nav
rather than the width of the
a
being hovered, despite selecting the
a
.

When setting the
left
property, it is static the left of the
nav
rather than left of the
a
. I need it to be relative to the item being hovered.

Here is the pertinent code:

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


and a CodePen

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

Any suggestions?
Thank you.

Seb Seb
Answer

You were almost there!

Missing part:

nav a {
  position: relative;
}

Without that the line positions to some element up in DOM (with position absolute, relative, fixed, or if missing to body).

As for 50% width, I’d do that:

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

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

}

Fork from your code: http://codepen.io/anon/pen/BzXKrB