Hey, I am Ajink, and today in this blog, we’re going to design a responsive navigation bar using HTML and CSS. A responsive navigation bar is crucial for providing a seamless user experience across various screen sizes.
HTML code : create an index.html file
<!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="style.css">
<title>Responsive Navigation Bar</title>
</head>
<body>
<nav class="navbar">
<div class="logo">Your Logo</div>
<ul class="nav-links">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</body>
</html>
CSS code : create a style.css
body {
margin: 0;
font-family: 'Arial', sans-serif;
}
.navbar {
background-color: #333;
padding: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
.logo {
color: #fff;
font-size: 1.5rem;
}
.nav-links {
list-style: none;
display: flex;
}
.nav-links li {
margin-right: 20px;
}
.nav-links a {
text-decoration: none;
color: #fff;
font-weight: bold;
}
/* Responsive styles */
@media screen and (max-width: 768px) {
.navbar {
flex-direction: column;
align-items: flex-start;
}
.nav-links {
margin-top: 10px;
order: 1;
display: none;
}
.nav-links.show {
display: flex;
}
.nav-links li {
margin: 0;
padding: 10px;
border-bottom: 1px solid #fff;
}
}
CSS Code Explanation:
- The CSS provides styling for the navigation bar, including background color, padding, and a flex layout.
- The
@media
query is used to apply styles specific to screens with a maximum width of 768px, making the navigation bar responsive. - When the screen size is less than or equal to 768px, the navigation links are hidden (
display: none;
) and are shown when the user clicks on the navigation icon.
JavaScript Code : script.js
document.addEventListener("DOMContentLoaded", function () {
const navbar = document.querySelector('.navbar');
const navLinks = document.querySelector('.nav-links');
navbar.addEventListener('click', function () {
navLinks.classList.toggle('show');
});
});
JavaScript Code Explanation:
- The JavaScript code adds a click event listener to the navigation bar.
- When the user clicks on the navigation bar, it toggles the
show
class on the navigation links, making them visible or hidden.
Conclusion:
In this blog, we successfully designed a responsive navigation bar using HTML, CSS, and a touch of JavaScript for mobile screens. You can customize the navigation links and styling to fit your website’s design. Don’t forget to subscribe to my YouTube channel at youtube.com/@ajink21 for more exciting tutorials.
Thanks for reading, and if you have any doubts, feel free to comment!