Landon Soo Hoo
Landon Soo Hoo

Reputation: 68

How do I make the navbar responsive depending on the viewport?

I want to make a responsive webpage. I want it to display a different nav based on the viewport. Here is the javascript that I have so far:

var shownav = document.getElementById('show-nav');

if (screen.width < "720"){
  shownav.style.display = 'block';
}

But for some reason, it does not work. Can you please help me?

Upvotes: 1

Views: 298

Answers (3)

abdel
abdel

Reputation: 1

@media only screen and (max-width: 720px) {
  #show-nav {
    display: block;
  }
}

Upvotes: 0

johannchopin
johannchopin

Reputation: 14873

You can achieve this without javascript by using a media-query:

#show-nav {
  display: none;
  background-color: red;
}

/* if screen width is smaller than 720px, #show-nav will be a block */
@media only screen and (max-width: 720px) {
  #show-nav {
    display: block;
  }
}
<nav id="show-nav">
  Navbar
</nav>

Upvotes: 2

MaxiGui
MaxiGui

Reputation: 6358

You could use only css to do so.

DEMO (make it full page)

body{
  margin: 0;
}
nav{
  width: 100vw;
  background:yellow;
}

@media only screen and (min-width: 720px){
  nav{
    background:red;
  }
}
<nav>
  <ul>
    <li>Welcome</li>
  </ul>
</nav

Upvotes: 0

Related Questions