【问题标题】:Text underline on hover pure css [duplicate]悬停纯CSS上的文本下划线[重复]
【发布时间】:2020-09-10 17:14:48
【问题描述】:

当用户将鼠标悬停在文本上时,我正在尝试使用纯 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>

【问题讨论】:

    标签: html css


    【解决方案1】:

    position: relative 应用于.title。否则,位置将与文档一起计算。

    .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>

    【讨论】:

    • 还有一个问题,下划线不是文字的宽度,如何解决?
    • @learningtoanimate 将display:inline-block 添加到.title
    • display: inline-block 会将宽度设置为内容。
    • 这行得通,但是这些段落并不都在自己的行中。我可以添加一个断路器,但有没有更有效的方法@ZohirSalak、@HansFelixRamos?
    • @learningtoanimate display:table 改为
    猜你喜欢
    • 2014-02-11
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2017-03-07
    • 2021-10-10
    相关资源
    最近更新 更多