Michael
Michael

Reputation: 2942

Responsive navigation menu with hiding on small screens in pure CSS

I want to create a simple navigation menu with a special feature:

I'm searching a solution without Javascript. I know about media queries in CSS but I don't know how to add a menu with this requirement.

This is the menu for example:

<nav>
    <ul>
        <li><a href="item1.html">item1</a></li>
        <li><a href="item2.html">item2</a></li>
        <li><a href="item3.html">item3</a></li>
        <li><a href="item4.html">item4</a></li>
    </ul>
</nav>

CSS:

/* default for all browsers */
nav>ul {
    padding: 0;
    margin: 0;
    list-style: none;
    background-color: #3d3d3d;
}
nav>ul>li>a {
    display: block;
    color: #ffffff;
}

@media only screen and (max-width: 360px) {
    /* mobile */
    /* WHAT NOW? */
}

@media only screen and (min-width: 361px) {
    nav>ul>li {
        /* bar layout */
        display: inline-block;
    }
}

fiddle: https://jsfiddle.net/1fg4qkx5/

Upvotes: 1

Views: 4251

Answers (1)

Giovanni Le Grand
Giovanni Le Grand

Reputation: 784

i have edited your jsfiddle and found a rather "Simple" solution for you,

jsfiddle

I have not (yet) found a way to do this completely without javascript to catch the button click.

to post out the results here:


HTML

<nav>
    <button class='hide-lg right'>
        &#9776;
    </button>
<ul>
    <li><a href="item1.html">item1</a></li>
    <li><a href="item2.html">item2</a></li>
    <li><a href="item3.html">item3</a></li>
    <li><a href="item4.html">item4</a></li>
</ul>

css

/* default for all browsers */
*{
  margin: 0;
  padding: 0;
}
body{
  min-width: 100%;
  min-height: 100%;
}

button{
  border:1px solid gray;
  background-color: transparent;
  display: inline-block;
}

.show{
  display: inline-block;
}
.right{
  float:right;
}
nav{
  background-color: #3d3d3d !important;
  color: #ffffff;
  height:auto;
  width: 100%;
  display: block;
}
nav>ul {
  padding: 0;
  margin: 0;
  list-style: none;
  background-color: #3d3d3d;
}
nav>ul>li>a {
  display: block;
  color: #ffffff;
}

@media only screen and (max-width: 360px) {
  .hide-lg{
    display:inline-block;
  }
  ul{
    display: none;
  }
  /* mobile */
  /* WHAT NOW? */
}

@media only screen and (min-width: 361px) {
  .hide-lg{
    display: none !important;
  }
  nav>ul{
    display: block;
  }
  nav>ul>li {
    /* bar layout */
    display: inline-block;
  }
  nav>ul>li>a{
    display: block;
    width:100%;
    height: 100%;
  }
}

Javascript/jQuery

$(document).ready(function(){
  $('button').click(function(){
      $('ul').toggleClass('show');
  });
});

I hope you find my answer helpfull, Giovanni

Upvotes: 1

Related Questions