DEV Community

Lens
Lens

Posted on

How to make a responsive Navbar with CSS

Making the Nav menu

First, we'll make the nav menu, we won't use an unordered list because it takes more CSS, so we'll just make a nav element with the selections of the menu as the children including a button. For the CSS we'll make the nav a flex row to align the children horizontally and then center all of the children. Finally, we'll give it font and a gap to space each menu selection.

<!--HTML Snippet-->
 <nav>
  <p>Home</p>
  <p>about</p>
  <p>Products</p>
  <p>Blog</p>
  <button>Sign up</button>
</nav>
Enter fullscreen mode Exit fullscreen mode
nav {
  display: flex;
  gap: 10%;
  justify-content: center;
  align-items: center;
  font-family: 'poppins', sans-serif;
  background-color: white;
}

nav > button {
/* Sign up button */
  background-color: transparent;
  border: solid 1px green;
  color: green;
  border-radius: 3px;
  height:  45px;
  transition: 0.3s;
}

nav > p {
  cursor: pointer;
}

  nav > button:hover {
/* Hover animation for the sign-up button*/
  background-color: green;
  color: white;
  border: none;
}
Enter fullscreen mode Exit fullscreen mode

Making the Nav menu responsive

To make the Nav menu responsive we'll need a media query. We'll make the rule a max-width of 500px meaning when the website is less than 500 pixels wide the change will happen. In the media query, we'll make it so the nav bar turns into a column, instead of using an absolute position or a translation we'll use the inset property to put the nav to the right. Inset basically is a property used to show how much an element covers the parent element, so inset: 0 0 0 77% means it doesn't cover 77% of the left side. We put the position to fixed so it stays to the right of the screen no matter how much you scroll, even though this wouldn't matter in this website when you make something like a landing page this is super important when making a website like this. Lastly, we'll put the width to 100% and give the menu selections a padding-left to center them.

@media (max-width: 500px) {
  nav {
    flex-direction: column;
    inset: 0 0 0 77%;
    height: 100%; 
    position: fixed;
    z-index: 5;
    font-size: 15px;
  }
 nav > button {
/* Styling the button*/
   width: 90px;
   padding: 0;
   color: white;
   background-color: green;
   position: relative;
   width: 4rem;
 }
/* To center the text*/
 nav > p {
  padding-left: 40%;
 }

Enter fullscreen mode Exit fullscreen mode


This is just the nav part of my example, so here's the full example of the responsive nav at this codepen. If you minimize it some more it'll change, but if you expand it you'll see it goes back to being horizontal.

Image of responsive nav




That's all I have to share for today! There are other ways to do this of course but I just wanted to show my way. I'll make a landing page this weekend, so follow me to quickly see that!

Top comments (0)