How to Create a Responsive Navigation Bar Using Only HTML & CSS

Here is how to create a Responsive Navigation Bar using HTML & CSS only

Step 1: HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Navigation Bar</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav class="navbar">
<div class="logo">MySite</div>
<input type="checkbox" id="menu-toggle">
<label for="menu-toggle" class="menu-icon">&#9776;</label>
<ul class="nav-links">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</body>
</html>

Step 2: CSS Code

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
}

body {
    background-color: #f5f5f5;
}

.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #333;
    padding: 15px 20px;
    color: white;
}

.logo {
    font-size: 1.5em;
    font-weight: bold;
}

.nav-links {
    list-style: none;
    display: flex;
}

.nav-links li {
    margin: 0 10px;
}

.nav-links a {
    text-decoration: none;
    color: white;
    padding: 10px 15px;
    transition: 0.3s;
}

.nav-links a:hover {
    background-color: #555;
    border-radius: 5px;
}

/* Mobile Menu */
.menu-icon {
    display: none;
    font-size: 2em;
    cursor: pointer;
}

#menu-toggle {
    display: none;
}

@media screen and (max-width: 768px) {
    .nav-links {
        display: none;
        flex-direction: column;
        background-color: #333;
        position: absolute;
        top: 60px;
        left: 0;
        width: 100%;
        padding: 10px 0;
    }

    .nav-links li {
        text-align: center;
        margin: 10px 0;
    }

    .menu-icon {
        display: block;
    }

    #menu-toggle:checked + .menu-icon + .nav-links {
        display: flex;
    }
}

How It Works:

  1. Desktop View: The navbar is displayed horizontally.
  2. Mobile View: A menu icon () appears, and clicking it shows the menu using a hidden checkbox technique.
  3. Pure CSS Toggle: The checkbox allows us to show/hide the navigation links without JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top