css折叠的导航栏
要创建一个简单的CSS折叠的导航栏,你可以使用HTML和CSS。以下是一个基本的例子:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collapsible Navigation Bar</title>
<style>
body {
font-family: Arial, sans-serif;
}
.navbar {
overflow: hidden;
background-color: #333;
}
.navbar a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.navbar a:hover {
background-color: #ddd;
color: black;
}
.navbar .icon {
display: none;
}
@media screen and (max-width: 600px) {
.navbar a:not(:first-child) {display: none;}
.navbar a.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 600px) {
.navbar.responsive {position: relative;}
.navbar.responsive a.icon {
position: absolute;
right: 0;
top: 0;
}
.navbar.responsive a {
float: none;
display: block;
text-align: left;
}
}
</style>
</head>
<body>
<div class="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">☰</a>
</div>
<script>
function myFunction() {
var x = document.querySelector(".navbar");
if (x.className === "navbar") {
x.className += " responsive";
} else {
x.className = "navbar";
}
}
</script>
</body>
</html>
CSS:
body {
font-family: Arial, sans-serif;
}
.navbar {
overflow: hidden;
background-color: #333;
}
.navbar a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.navbar a:hover {
background-color: #ddd;
color: black;
}
.navbar .icon {
display: none;
}
@media screen and (max-width: 600px) {
.navbar a:not(:first-child) {display: none;}
.navbar a.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 600px) {
.navbar.responsive {position: relative;}
.navbar.responsive a.icon {
position: absolute;
right: 0;
top: 0;
}
.navbar.responsive a {
float: none;
display: block;
text-align: left;
}
}
这段代码包括了一个简单的水平导航栏,以及一个可以折叠/展开的菜单图标。当屏幕宽度小于600像素时,除第一个链接外的所有链接会被隐藏,同时显示菜单图标,点击该图标可以切换导
评论已关闭