1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>纯CSS导航栏下划线跟随效果</title> 8 </head> 9 <style> 10 *{ 11 margin: 0; 12 padding: 0; 13 } 14 html, 15 body{ 16 width: 100%; 17 height: 100%; 18 } 19 ul{ 20 display: flex; 21 position: absolute; 22 top: 50%; 23 left: 50%; 24 transform: translate(-50%, -50%); 25 } 26 li{ 27 position: relative; 28 padding: 1em 2em; 29 font-size: 24px; 30 list-style: none; 31 white-space:nowrap; 32 } 33 li::after{ 34 content: ''; 35 position: absolute; 36 bottom: 0; 37 width: 0; 38 height: 2px; 39 background-color: #000; 40 transition: .5s all linear; 41 } 42 li:hover::after{ 43 width: 100%; 44 } 45 li::after{ 46 left: 100%; /*选中项上一个下划线收回的方向,从左往右收线*/ 47 } 48 li:hover::after{ 49 left: 0; /*选中项下划线出线的方向,从左往右出线*/ 50 } 51 li:hover ~ li::after { 52 left: 0; /*选中项下一个下划线出线的方向,从左往右收线*/ 53 } 54 </style> 55 <body> 56 <ul> 57 <li>纯CSS导航栏</li> 58 <li>导航菜单项</li> 59 <li>被划过</li> 60 <li>下划线跟随</li> 61 </ul> 62 </body> 63 </html>