今天学习了使用HTML+CSS实现下拉菜单效果,在这个例子中,我学到了如下知识点:
- 设置背景图片(background-image、background-size)
- 如何让无序列表横向显示(float:left)
- 如何实现鼠标停留时,出现下拉菜单(:hover)
- 相对定位和绝对定位(position:relative、absolute)
html和css代码分别如下:
<!DOCTYPE html> <html> <head> <title>Dropdown menu</title> <link rel="stylesheet" type="text/css" href="index5.css"> <body> <nav> <p>ptravels</p> <ul> <li><a href="#">Home</a></li> <li><a href="#">Portfolio</a> <ul> <li><a href="#">Data analysis</a></li> <li><a href="#">Artifical inteligence</a></li> <li><a href="#">Web development</a></li> </ul> </li> <li><a href="#">About me</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </body> </html>
* { margin: 0; padding: 0; } body { background-image: url('images/banner.jpg'); background-size: cover; } nav { width: 100%; height: 60px; background-color: #fff; } nav p { font-family: arial; font-size: 24px; text-transform: uppercase; line-height: 55px; padding: 0 20px; float: left; } nav ul { float: left; } nav ul li { float: left; list-style: none; position: relative; } nav ul li a { display: block; font-family: arial; font-size: 14px; padding: 22px 10px; text-decoration: none; } nav ul li ul { display: none; position: absolute; background-color: #fff; padding: 10px; border-radius: 0px 0px 4px 4px; } nav ul li:hover ul { display: block; } nav ul li ul li { width: 160px; border-radius: 4px; } nav ul li ul li a { padding: 8px 10px; } nav ul li ul li a:hover { background-color: #f3f3f3; }
最终效果:
参考链接:
[1] https://www.youtube.com/watch?v=rgUp302f_lY&index=41&list=PL0eyrZgxdwhwNC5ppZo_dYGVjerQY3xYU