gpt4 book ai didi

css - 如何在文本正下方使用伪元素绘制一条线并忽略填充?

转载 作者:行者123 更新时间:2023-11-28 11:01:53 25 4
gpt4 key购买 nike

我想在链接下面画一条线并在上面应用动画,所以我使用了伪元素。它按预期生成线条,但如果链接周围有较大的填充,则线条看起来很远。有没有办法忽略填充并在文本正下方画线?

a {
position: absolute;
padding: 20px 0;
top: 50%;
left: 50%;
margin-top: -30px;
margin-left: -30px;
line-height: 20px;
}

a:after {
position: absolute;
bottom: 0;
left: 0;
width: 0;
content: '';
transition: width .3s;
display: block;
}

a:hover:after {
width: 100%;
border-top: 1px solid #333;
}
<a>Link Text</a>

最佳答案

您可以删除绝对位置,因为伪设置在 :after 上,因此它紧跟在文本之后。

a {
position: absolute;
padding: 20px 0;
top: 50%;
left: 50%;
margin-top: -30px;
margin-left: -30px;
line-height: 20px;
border: 1px solid aqua;
}

a:after {
content: "";
display: block;
border-top: 1px solid #333;
width: 0;
transition: width .3s;
}

a:hover:after {
width: 100%;
}
<a>Link Text</a>

旁注,在手机、平板电脑等触摸设备上,您可能会遇到类似悬停效果的双击行为。添加这个来解决这个问题:

@media (hover: none) {
a:hover:after {
display: none;
}
}

另外,效果也可以用linear-gradient()来完成,例子:

a {
display: inline-block;
text-decoration: none;
border: 1px solid aqua;
font-size: 16px;
padding: 20px 0;
background-image: linear-gradient(to bottom, blue, blue);
background-position: 0 38px; /*adjust this based on font-size and padding*/
background-size: 0 1px;
background-repeat: no-repeat;
transition: background-size .3s;
}

a:hover {
background-size: 100% 1px;
}
<a href="#">Link text</a>

关于css - 如何在文本正下方使用伪元素绘制一条线并忽略填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48625258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com