我前一段时间一直在练习CSS,并试图在不使用bootstrap或jQuery的情况下实现一个简单的下拉菜单。
问题是,我无法完全模仿下拉菜单,如下图所示。
期待结果
当前结果
<div id="menu">
<a href="#" class="menu-toggle">
<span></span>
<span></span>
<span></span>
</a>
<ul id="dropdown-menu">
<li class="dropdown-item">
<a href="#about">About</a>
</li>
<li class="dropdown-item">
<a href="#travel">Travel</a>
</li>
<li class="dropdown-item">
<a href="#food">Food</a>
</li>
</ul>
</div>
答案 0 :(得分:1)
所以你的小提琴演示中有很多不准确之处,所以我想我会把它改写成你想要的结果,然后你可以从那里开始。 css下拉菜单背后的理论是包含元素将具有某个位置(在这种情况下,我将其定位为相对位置),下拉菜单将在包含元素内部具有绝对位置,并且显示为none。然后,当您将鼠标悬停在包含元素上时,下拉列表将显示一个块,因此这里是您尝试实现的实例。
#menu{
position:relative;
display:inline-block;
/*font size 0 removes white space from inline block elements add font size to the dropdown menu*/
font-size:0;
}
#menu .menu-toggle {
padding: 10px;
background: rgba(255,255,255,0.9);
border:1px solid rgb(220,220,220);
display:inline-block;
}
#menu .menu-toggle span{
display:block;
margin: 3px 0px;
width: 18px;
height: 3px;
background: #33333D;
}
#dropdown-menu{
display:none;
list-style-type:none;
margin:0;
padding:0;
position:absolute;
top:100%;
left:0;
border:1px solid rgb(220,220,220);
font-size:16px;
}
#menu:hover #dropdown-menu{
display:block;
}
#dropdown-menu li a{
display:block;
padding:5px 15px;
color:inherit;
text-decoration:none;
}
<div id="menu">
<a class="menu-toggle">
<span></span>
<span></span>
<span></span>
</a>
<ul id="dropdown-menu">
<li class="dropdown-item">
<a href="#about">About</a>
</li>
<li class="dropdown-item">
<a href="#travel">Travel</a>
</li>
<li class="dropdown-item">
<a href="#food">Food</a>
</li>
</ul>
</div>
答案 1 :(得分:1)
<div class="menu-area">
<div id="menu">
<a href="#" class="menu-toggle">
<span></span>
<span></span>
<span></span>
</a>
<ul id="dropdown-menu">
<li class="dropdown-item">
<a href="#about">About</a>
</li>
<li class="dropdown-item">
<a href="#travel">Travel</a>
</li>
<li class="dropdown-item">
<a href="#food">Food</a>
</li>
</ul>
</div>
</div>
.menu-area {
width: 220px;
position: relative;
text-align: right;
}
#menu {
display: inline-block;
}
a.menu-toggle {
width: 30px;
height: 30px;
padding: 5px 10px;
display: inline-block;
border: 1px solid #ddd;
z-index: 9;
background: #fff;
position: relative;
transition: .3s;
}
#menu:hover a.menu-toggle {
border-bottom: 0;
}
a.menu-toggle span {
height: 3px;
display: block;
margin-top: 5px;
background: #555;
}
ul#dropdown-menu {
position: absolute;
top: 50px;
width: 218px;
transition: .3s;
opacity: 0;
visibility: hidden;
padding: 20px 0px;
border: 1px solid #ddd;
margin: 0;
text-align: left;
left: 0;
}
#menu:hover ul#dropdown-menu {
top: 40px;
opacity: 1;
visibility: visible;
}
ul#dropdown-menu li {
margin: 0;
padding: 5px 30px;
display: block;
}
ul#dropdown-menu li a {
display: inline-block;
transition: .3s;
color: #333;
text-decoration: none;
font-size: 18px;
}
ul#dropdown-menu li a:hover {
color: #666;
}