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

独自空忆成欢 提交于 2020-12-13 03:00:59

问题


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?


回答1:


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>



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/64375491/how-do-i-make-the-navbar-responsive-depending-on-the-viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!