Others




Create Responsive NavBar using CSS


This example shows how to create simple responsive NavBar using css and JavaScript.we have to use CSS media query for responsive NavBar.

Example : style.css
html,body{
  margin: 0;
  padding: 0;
  font-family: cambria;
}
.navbar{
  width: 100%;
  padding: 20px;;
  background-color: rgb(6, 128, 128);
  box-sizing: border-box;
}
.navbar .navbar-header{
  color: white;
  font-size: 20px;
  text-decoration: none;
}
/*Desktop*/
@media (min-width:600px){
  .navbar .navbar-item{
    position: absolute;
    right: 0;
    top:5px;
  }
  .navbar .navbar-item ul li{
    display: inline;
    margin-right: 15px;
  }
  .navbar .navbar-item ul li a{
    color: white;
    text-decoration: none;
    font-size: 16px;
  }
  .navbar .navbar-item ul li a:hover{
    color:#ccc;
  }
  .navbar-btn{
    display:none;
  }
}
@media (max-width:600px){
  .navbar .navbar-item ul {
    list-style-type: none;
    padding: 0;
  }

  .navbar .navbar-item ul li{
    margin-top: 15px;
    padding-bottom: 15px;
    border-bottom:1px solid rgba(255,255,255,0.2);
  }
  .navbar .navbar-item ul li a{
    color: white;
    text-decoration: none;
    font-size: 16px;
  }
  .navbar-btn{
    border:none;
    background: none;
    border:1px solid white;
    padding:5px;
    position: absolute;
    right:10px;
    top:15px;
    cursor: pointer;
  }
  .navbar-btn span{
    display: block;
    width: 20px;
    border-top:1px solid white;
  }
  .navbar-btn span:not(:last-child){
    margin-bottom: 5px;

  }
  .hide{
    display: none;
  }
}
Example : index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Responsive Navbar Using CSS</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="navbar">
    <a href="#" class="navbar-header">Navbar</a>
    <button class='navbar-btn'>
      <span></span>
      <span></span>
      <span></span>
    </button>
    <div class='navbar-item hide'>
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Product</a></li>
        <li><a href="#">About Us</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
    </div>
  </div>
  <script>
    document.querySelector(".navbar-btn").onclick=function(){
       document.querySelector(".navbar-item").classList.toggle("hide");
    }
  </script>
</body>
</html>
Try it Yourself