悬停纯CSS上的文字下划线[重复]

当用户将鼠标悬停在文本上方时,我试图使用纯CSS在文本上加一个从中心开始的渐变下划线。

它可以正常工作,但是由于某种原因,下划线出现在文档的底部而不是文本的每一行,我不知道为什么会这样。

任何指针将不胜感激。

.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>
评论
  • T和T
    T和T 回复

    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>