1.最简单的下拉菜单
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
padding: 12px 16px;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
<div class="dropdown">
<span>鼠标移动到我这!</span>
<div class="dropdown-content">
<p>菜鸟教程</p>
<p>www.runoob.com</p>
</div>
</div>
鼠标移上去的时候显示,不然不显示。
并且加了个 box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);搞出点阴影,好像是弹出的似的,其实就是显示而已。
2.下拉菜单,并且改变选中颜色
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #f1f1f1//改变内容项的颜色
}
.dropdown:hover .dropdown-content {
display: block;//鼠标在上的时候显示
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;//改变button的颜色
}
</style>
<div class="dropdown">
<button class="dropbtn">下拉菜单</button>
<div class="dropdown-content">
<a href="http://www.runoob.com">菜鸟教程 1</a>
<a href="http://www.runoob.com">菜鸟教程 2</a>
<a href="http://www.runoob.com">菜鸟教程 3</a>
</div>
</div>
3.下拉菜单是从左边还是右边弹出
<style>
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
right: 0;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
</style>
<div class="dropdown" style="float:left;">
<button class="dropbtn">左</button>
<div class="dropdown-content" style="left:0;">
<a href="#">菜鸟教程 1</a>
<a href="#">菜鸟教程 2</a>
<a href="#">菜鸟教程 3</a>
</div>
</div>
<div class="dropdown" style="float:right;">
<button class="dropbtn">右</button>
<div class="dropdown-content" style="left:0;">
<a href="#">菜鸟教程 1</a>
<a href="#">菜鸟教程 2</a>
<a href="#">菜鸟教程 3</a>
</div>
</div>
注意:写在html中的style="left:0;",就是指从这个元素的左边偏移0个位置弹出。下一个是错的,应该为right:0弹出,代码只是为了演示。其它的和代码2基本一样的。