1 展示
2 代码
2.1 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>滑动跟踪导航栏</title>
<link rel="stylesheet" href="./nav.css">
</head>
<body>
<div class="nav">
<ul>
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JS</a></li>
<li><a href="#">Jquery</a></li>
<li><a href="#">VUE</a></li>
<li><a href="#">PHP</a></li>
<div class="nav-box"></div>
</ul>
</div>
</body>
</html>
2.2CSS
*{
list-style: none;
padding: 0;
margin: 0;
text-decoration: none;
}
body{
display: flex;
justify-content: center;
align-items:center;
height: 100vh;
background-color: #8da1f8;
}
.nav{
width: 1200px;
height: 70px;
position: relative;
top: 0;
box-shadow: 0 5px 20px rgba(0,0,0,.5);
border-radius: 10px;
background-color: #fff;
}
.nav ul{
width: 100%;
height: 100%;
display: flex;
align-items: center;
right: 5%;
}
.nav ul .nav-box{
position: absolute;
bottom: 0;
left: 0;
/* 如果导航栏就六个导航,那么每个导航的宽度都是整个导航的六分之一 */
width: calc((100%/6)*1);
height: 10px;
border-radius: 2px;
transition: .5s;
}
.nav ul li{
width: 100%;
text-align: center;
}
.nav ul li a{
color: rgb(70, 100, 180);
font: 100 30px '';
display: block;
width: 100%;
height: 100%;
line-height: 70px;
}
.nav ul li:nth-child(1):hover~.nav-box{
left: calc((100%/6)*0);
background-color: rgb(250, 190, 250);
}
.nav ul li:nth-child(2):hover~.nav-box{
left: calc((100%/6)*1);
background-color: red;
}
.nav ul li:nth-child(3):hover~.nav-box{
left: calc((100%/6)*2);
background-color: #d18df8;
}
.nav ul li:nth-child(4):hover~.nav-box{
left: calc((100%/6)*3);
background-color: #ffb1b1;
}
.nav ul li:nth-child(5):hover~.nav-box{
left: calc((100%/6)*4);
background-color: #8da1f8;
}
.nav ul li:nth-child(6):hover~.nav-box{
left: calc((100%/6)*5);
background-color: #7df88e;
}
3 部分解释
3.1 hover的简单介绍(+,~的用法)
注意hover后面一帮都是控制子元素
hover更改同级(兄弟)元素属性:
更改兄弟元素又分两种情况:
(1)需要更改的兄弟元素是当前元素的相邻元素,也就是说紧接着当前元素。那么写法如下:
.item-1:hover +.item-2{
background-color:#50ff00;
}
(2)需要改变的兄弟元素不是当前元素的邻接元素(如上面演示图中的 item-1 和 item-3)。
这种情况就需要改一下写法,用上面的 “+” 就行不通了,得用 “~”。写法如下:
.item-1:hover ~.item-3>.item-3-child{
background-color:#50ff00;
}