三層導航是網頁設計中常見的導航欄風格,它能夠讓網頁更加清晰明了。在實現三層導航時,我們需要使用CSS來布局和樣式化,下面是三層導航的CSS代碼:
/*一級導航樣式*/ .nav1 { display: flex; justify-content: space-between; align-items: center; background-color: #333; padding: 10px 20px; } /*一級導航文字樣式*/ .nav1 a { color: white; font-size: 1.2rem; text-transform: uppercase; text-decoration: none; } /*二級導航樣式*/ .nav2 { background-color: #ddd; display: none; position: absolute; width: 100%; top: 100%; left: 0; } /*三級導航樣式*/ .nav3 { background-color: #f0f0f0; display: none; position: absolute; width: 100%; top: 0; left: 100%; } /*二級導航和三級導航出現動畫*/ .nav1:hover .nav2 { display: block; animation: fadein 0.5s; } .nav2:hover + .nav3, .nav2:focus + .nav3 { display: block; animation: fadein 0.5s; } /*鼠標離開二級導航和三級導航隱藏*/ .nav2:hover, .nav3:hover { display: block; } .nav2:not(:hover) { animation: fadeout 0.5s; animation-fill-mode: forwards; } .nav3:not(:hover) { animation: fadeout 0.5s; animation-fill-mode: forwards; } /*動畫效果*/ @keyframes fadein { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeout { from { opacity: 1; } to { opacity: 0; } }
這段代碼使用了flex布局來實現一級導航欄的水平排列和垂直居中。二級導航和三級導航使用了絕對定位,并通過:hover和:focus選擇器實現出現和隱藏的動畫效果。