How to create a responsive navbar with a toggle button for small screens in CSS

Arif Billah Babu

         

  CSS



Image not found!!

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:

  1. HTML Structure:
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">&#9776;</div> </div> </header> <script src="script.js"></script> </body> </html>
  1. CSS Styles (styles.css):
css
body { 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 */ } }
  1. JavaScript (script.js):
javascript
document.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.