0

I'm trying to use purely CSS to underline my text with a gradient from the center when a user hovers over it.

It's working but for some reason the underline appears at the bottom of the document rather than on each line of text and I can't figure out why this is happening.

Any pointers would be appreciated.

.title {
    font-family: 'Roboto', sans-serif;
    font-size: 20px;
    margin-top: 2px;
    margin-bottom: 2px;
    line-height: 1em;
    text-transform: uppercase;
}

.title:after {    
    background: none repeat scroll 0 0 transparent;
    bottom: 0;
    content: "";
    display: inline;
    height: 5px;
    left: 50%;
    position: absolute;
    background: linear-gradient(-45deg, #FFFFFF, #000000);
    transition: width 0.3s ease 0s, left 0.3s ease 0s;
    width: 0;
}

.title:hover:after { 
    width: 100%; 
    left: 0; 
}
<head>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
</head>

<p class="title" onclick="location.href='1'">Hover to underline</p>
<p class="title" onclick="location.href='2'">Hover to underline</p>
<p class="title" onclick="location.href='3'">Hover to underline</p>
<p class="title" onclick="location.href='4'">Hover to underline</p>

1 Answers1

5

Apply position: relative to .title. Otherwise the position is calculated with the document.

.title {
    position: relative;
    font-family: 'Roboto', sans-serif;
    font-size: 20px;
    margin-top: 2px;
    margin-bottom: 2px;
    line-height: 1em;
    text-transform: uppercase;
}

.title:after {    
    background: none repeat scroll 0 0 transparent;
    bottom: 0;
    content: "";
    display: inline;
    height: 5px;
    left: 50%;
    position: absolute;
    background: linear-gradient(-45deg, #FFFFFF, #000000);
    transition: width 0.3s ease 0s, left 0.3s ease 0s;
    width: 0;
}

.title:hover:after { 
    width: 100%; 
    left: 0; 
}
<head>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
</head>

<p class="title" onclick="location.href='1'">Hover to underline</p>
<p class="title" onclick="location.href='2'">Hover to underline</p>
<p class="title" onclick="location.href='3'">Hover to underline</p>
<p class="title" onclick="location.href='4'">Hover to underline</p>
Hans Felix Ramos
  • 4,264
  • 3
  • 16
  • 40