我刚开始学习HTML/CSS并且正在制作个人网站。我遇到了创建下拉汉堡菜单的问题。在移动端大小调整时,我已经设置好了标题栏,但是当我点击汉堡图标时,菜单却与主导航栏对齐。我想让它嵌套在主菜单下方,并具有100%的宽度。此外,我还想在用户完成查看后添加“x”符号来关闭它。希望我解释得足够清楚,我会发布CodePen链接。
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
body {
background-color: #EFF0EC
}
.header {
padding-left: 30px;
background-color: #FFFFFF;
padding-top: 18px;
padding-bottom: 18px;
}
h1 {
font-size: 36px;
font-family: Buenard, Times, serif;
background-color: #FFFFFF
float: left;
display: inline;
}
ul.topnav {
list-style-type: none;
display: inline;
float: right;
margin: auto;
padding: 0;
overflow: hidden;
}
li a {
color: #000;
text-decoration: none;
display: inline-block;
transition: 0.3s;
}
li a:hover {
color: #80B198;
}
li {
font-size: 22px;
font-family: Lato, Arial sans-serif;
padding: 10px 16px;
display: inline-block;
margin: auto;
}
ul. topnav li.icon {
display: none;
}
/* Smartphone-size screens */
@media (max-width: 767px) {
ul.topnav li {display: none;}
ul.topnav li.icon {
display: inline-block;
}
ul.topnav.responsive {position: relative;}
ul.topnav.responsive li.icon {
position: absolute;
right: 0;
top: 0;
}
ul.topnav.responsive li {
float: none;
display: inline;
}
ul.topnav.responsive li a {
display: block;
text-align: left;
}
}
<body>
<div class="header">
<h1>Lorem Ipsum</h1>
<ul class="topnav" id="myTopnav">
<li><a class="active" href="#portfolio">Portfolio</a></li>
<li><a href="#about">About Me</a></li>
<li><a href="#contact">Contact</a></i>
<li class="icon">
<a href="javascript:void(0);" onclick="myFunction()">☰</a>
</li>
</ul>
</div>
</body>