【问题标题】:How do I animate a link underline to the width of the link, not the ul?如何为链接的宽度设置下划线动画,而不是 ul?
【发布时间】:2019-11-12 07:34:53
【问题描述】:
我有以下链接悬停动画:
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
}
body {
font-family: Arial;
background-color: red;
}
ul {
list-style-type: none;
width: 33vw;
margin: 0;
padding: 0;
}
li {
margin: 0 10px;
padding: 2px;
}
a {
text-decoration: none;
color: white;
font-size: 25px;
}
a::after {
content: "";
width: 0;
height: 2px;
background-color: white;
display: block;
transition: width 0.5s;
}
a:hover::after {
width: 100%;
}
<!DOCTYPE html>
<html>
<body>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Contact</a></li>
</ul>
</body>
</html>
在上面的 sn-p 中,当我将鼠标悬停在每个链接上时,下划线会正确动画。但是,下划线在ul 的宽度处结束,而不是在每个链接本身的宽度处(例如,如果我将鼠标悬停在“主页”链接上,动画下划线会一直越过“主页”一词本身到ul 的末尾)。我应该如何更改 a::after 或 a:hover::after 伪元素的 CSS 以获得我正在寻找的行为?
【问题讨论】:
标签:
html
css
css-animations
underline
【解决方案1】:
只需在你的风格中使用内联块
a {
display: inline-block;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
}
body {
font-family: Arial;
background-color: red;
}
ul {
list-style-type: none;
width: 33vw;
margin: 0;
padding: 0;
}
li {
margin: 0 10px;
padding: 2px;
}
a {
text-decoration: none;
color: white;
font-size: 25px;
display: inline-block;
}
a::after {
content: "";
width: 0;
height: 2px;
background-color: white;
display: block;
transition: width 0.5s;
}
a:hover::after {
width: 100%;
}
<!DOCTYPE html>
<html>
<body>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Contact</a></li>
</ul>
</body>
</html>
【解决方案2】:
制作链接inline-block
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
}
body {
font-family: Arial;
background-color: red;
}
ul {
list-style-type: none;
width: 33vw;
margin: 0;
padding: 0;
}
li {
margin: 0 10px;
padding: 2px;
}
a {
text-decoration: none;
color: white;
font-size: 25px;
display: inline-block;
}
a::after {
content: "";
width: 0;
height: 2px;
background-color: white;
display: block;
transition: width 0.5s;
}
a:hover::after {
width: 100%;
}
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Contact</a></li>
</ul>