Creating a responsive navbar with a toggle button for small screens typically involves using media queries and some JavaScript to handle the toggle functionality. Here's a simple example using HTML, CSS, and JavaScript:
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Responsive Navbar</title>
</head>
<body>
<header>
<div class="navbar">
<div class="logo">Your Logo</div>
<nav class="nav-links">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Contact</a>
</nav>
<div class="toggle-button">☰</div>
</div>
</header>
<script src="script.js"></script>
</body>
</html>
cssbody {
margin: 0;
font-family: 'Arial', sans-serif;
}
header {
background-color: #333;
padding: 15px;
color: #fff;
}
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
}
.logo {
font-size: 1.5rem;
}
.nav-links {
display: flex;
}
.nav-links a {
color: #fff;
text-decoration: none;
padding: 0 15px;
}
.toggle-button {
font-size: 1.5rem;
cursor: pointer;
display: none; /* initially hidden on larger screens */
}
/* Media query for small screens */
@media only screen and (max-width: 768px) {
.nav-links {
display: none; /* hide nav links on small screens by default */
flex-direction: column;
width: 100%;
position: absolute;
top: 60px;
left: 0;
background-color: #333;
}
.nav-links.show {
display: flex; /* show nav links when .show class is added */
}
.nav-links a {
padding: 15px;
text-align: center;
width: 100%;
box-sizing: border-box;
border-bottom: 1px solid #555;
}
.toggle-button {
display: block; /* show toggle button on small screens */
}
}
javascriptdocument.addEventListener('DOMContentLoaded', function () {
const toggleButton = document.querySelector('.toggle-button');
const navLinks = document.querySelector('.nav-links');
toggleButton.addEventListener('click', function () {
navLinks.classList.toggle('show');
});
});
This example uses a media query to hide and show the navigation links and toggle button based on the screen size. The JavaScript adds a class to the navigation links when the toggle button is clicked, toggling their visibility. Adjust the styles and structure according to your specific needs.