Responsive Navbar in CSS


A CSS Navbar (Navigation Bar) is a user interface element that typically contains links to various sections of a website. It's an essential part of a website's design, providing users with an easy way to navigate through different pages or content.

Navbars can be styled and positioned in various ways using CSS to create a seamless and visually appealing navigation experience.

Responsive Navbar

A responsive navbar adapts to different screen sizes, typically collapsing into a hamburger menu on smaller screens.

<style>
   .responsive-navbar {
      list-style-type: none;
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #333;
   }

   .responsive-navbar li {
      float: left;
   }

   .responsive-navbar li a {
      display: block;
      color: white;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
   }

   .responsive-navbar li a:hover {
      background-color: #111;
   }

   .responsive-navbar .icon {
      display: none;
   }

   @media screen and (max-width: 600px) {
      .responsive-navbar li:not(:first-child) {display: none;}
      .responsive-navbar li.icon {
         float: right;
         display: block;
      }
   }

   @media screen and (max-width: 600px) {
      .responsive-navbar.responsive {position: relative;}
      .responsive-navbar.responsive li.icon {
         position: absolute;
         right: 0;
         top: 0;
      }
      .responsive-navbar.responsive li {
         float: none;
         display: block;
         text-align: left;
      }
   }
</style>
<nav>
   <ul class="responsive-navbar">
      <li><a href="#home">Home</a></li>
      <li><a href="#services">Services</a></li>
      <li><a href="#about">About</a></li>
      <li><a href="#contact">Contact</a></li>
      <li class="icon">
         <a href="javascript:void(0);" onclick="toggleMenu()">☰</a>
      </li>
   </ul>
</nav>
<p> Inspect and resize the browser to see the output</p>
<script>
   function toggleMenu() {
      var x = document.getElementsByClassName("responsive-navbar")[0];
      if (x.className === "responsive-navbar") {
         x.className += " responsive";
      } else {
         x.className = "responsive-navbar";
      }
   }
</script>