[HTML/CSS]导航栏的下划线跟随效果

时间:2022-03-30 06:07:55

[HTML/CSS]导航栏的下划线跟随效果

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>纯CSS导航栏下划线跟随效果</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
html,
body{
width: 100%;
height: 100%;
}
ul{
display: flex;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
li{
position: relative;
padding: 1em 2em;
font-size: 24px;
list-style: none;
white-space:nowrap;
}
li::after{
content: '';
position: absolute;
bottom: 0;
width: 0;
height: 2px;
background-color: #000;
transition: .5s all linear;
}
li:hover::after{
width: 100%;
}
li::after{
left: 100%; /*选中项上一个下划线收回的方向,从左往右收线*/
}
li:hover::after{
left: 0; /*选中项下划线出线的方向,从左往右出线*/
}
li:hover ~ li::after {
left: 0; /*选中项下一个下划线出线的方向,从左往右收线*/
}
</style>
<body>
<ul>
<li>纯CSS导航栏</li>
<li>导航菜单项</li>
<li>被划过</li>
<li>下划线跟随</li>
</ul>
</body>
</html>