我有以下链接悬停动画:
*,
*::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>
在以上代码段中,当我将鼠标悬停在每个链接上时,下划线会正确设置动画效果。但是,下划线在ul
的宽度处结束,而不是在每个链接本身的宽度处结束(例如,如果我将鼠标悬停在“主页”链接上,则动画下划线会超出单词“主页”本身,所有ul
末尾的方式。我该如何更改a::after
或a:hover::after
伪元素的CSS,以便获得所需的行为?
答案 0 :(得分: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>
答案 1 :(得分: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>