Wednesday, November 4, 2015

Making a responsive navigation without any additional css framework

This small tutorial will show you how to create a simple responsive navigation that works for any device.





The idea is like this
  1.  Create a navigation for mobile
  2.  Create another navigation for desktop
  3.  Control those navigation s with media queries
  4.  Control mobile-menu opening and closing with javascript (jquery)

1. Creating a navigation for mobile devices


HTML for mobile navigaition


<div class="mobile-nav">
    <a href="#" class="nav-btn">Menu</a>
    <ul>
        <li >ITEM 1</li>
        <li >ITEM 2</li>
        <li >ITEM 3</li>
    </ul>
</div>


CSS for mobile navigation


.mobile-nav {
    position:relative;
}
.mobile-nav ul, .mobile-nav .nav-btn  {
    position:absolute;
    right:0;
}
.mobile-nav ul {
    list-style:none;
    display:none; // we control this using javascript
    padding:10px;
    background-color:#ddd;
}
.mobile-nav ul li {
    padding-top:5px;
    padding-bottom:5px;
}


2. Creating navigation for desktops


HTML for desktop navigation


<div class="desktop-nav">
     <ul>
        <li >ITEM 1</li>
        <li >ITEM 2</li>
        <li >ITEM 3</li>
    </ul>
</div>


CSS for desktop navigation


.desktop-nav ul {
    list-style:none;
    padding:20px;
    background-color:#ddd;
}
.desktop-nav ul li {
    display:inline;
    padding:5px;
    background-color:#fafafa;
    border-radius:3px;
}


3. CSS: Media queries to control their appearance


Also see controlling elements visibility with bootstrap's classes

By default mobile navigation should be hidden, so make it to display none.

.mobile-nav {
    display:none;
}


This is the control we have for any screens that are less than or equal to 600px.

So, hide desktop nav for smaller screens, and show mobile nav.

@media (max-width: 600px) {
    .desktop-nav {
        display:none;
    }
    .mobile-nav {
        display:block;
    }
}


4. Opening and closing of mobile menu


var navBtn = $('.nav-btn');

navBtn.click(function() {                  
    $('.mobile-nav ul').toggle();
});


Fiddle available here.. http://jsfiddle.net/mannemvamsi/vzvcrenq/

Checkout more css tutorials

And subscribe for my updates..!!

No comments:

Post a Comment