1.效果展示(颜色仅为了看出效果,可根据情况自行修改)
2.html代码
<ul>
<li class="active">
<a href="">option1</a>
</li>
<li>
<a href="">option2</a>
</li>
<li>
<a href="">option4</a>
</li>
<li>
<a href="">option5</a>
</li>
<li>
<a href="">option5</a>
</li>
</ul>
3.CSS代码
- 利用css3的伪元素(::after)来绘画下划线
- 代码如下
/* 采用flex布局 */ ul { display: flex; width: 100%; height: 60px; background-color: #f2f2f2; list-style: none; } li { flex: 1 1; } li a { display: block; height: 60px; line-height: 60px; text-decoration: none; text-align: center; } /* 添加透明的下划线 位置在最后一个li下面,可通过修改background查看 设置position为relative 添加CSS3的过度效果 相对位置为left:0% */ li:last-child::after { position: relative; content: ''; width: 100%; height: 3px; background: transparent; display: block; transition: .3s ease; left: 0; } /* 设置选中链接下划线颜色与位置 */ li:nth-child(1).active~:last-child::after { background-color: #FF0000; left: -400%; /* 通过left使下划线向右移动4个li的大小距离 */ } li:nth-child(2).active~:last-child::after { background-color: #FFC000; left: -300%; /* 通过left使下划线向右移动3个li的大小距离 */ } li:nth-child(3).active~:last-child::after { background-color: #7030A0; left: -200%; /* 通过left使下划线向右移动2个li的大小距离 */ } li:nth-child(4).active~:last-child::after { background-color: #92D050; left: -100%; /* 通过left使下划线向右移动1个li的大小距离 */ } li:nth-child(5).active:last-child::after { background-color: #0b8793; left: 0; } /* 设置鼠标悬停下划线颜色与位置 */ li:nth-child(1):hover~:last-child::after { background-color: #FF0000; left: -400%; } li:nth-child(2):hover~:last-child::after { background-color: #FFC000; left: -300%; } li:nth-child(3):hover~:last-child::after { background-color: #7030A0; left: -200%; } li:nth-child(4):hover~:last-child::after { background-color: #92D050; left: -100%; } li:nth-child(5):last-child:hover::after { background-color: #0b8793 ; left: 0; } /* 链接字体颜色 */ li:nth-child(1) a { color: #FF0000; } li:nth-child(2) a { color: #FFC000; } li:nth-child(3) a { color: #7030A0; } li:nth-child(4) a { color: #92D050; } li:nth-child(5) a { color: #00B0F0; }