Thursday, November 20, 2014

CSS Tabs Navigation Tricks

Developing a tabs navigation with CSS holds some simple tricks, but most of the front-end guys end up getting the results in an inappropriate way. Here's what you need to know about it -
I. The margin-bottom: -1px to the <li> element
II. The border and background to the <a> element
III. Change in border and background in the <a> element when <li> has .active class

HTML: 

CSS: 
ul{ margin: 0; padding: 0; list-style: none; border-bottom: 1px solid #ddd; 
}
ul:before, ul:after{
    content: ""; display: table;
}
ul:after{
    clear: both;
}
/**/
ul li{ 
    float: left; 
    margin: 0 4px -1px 4px;                /*Trick 1*/
}
ul li a{ 
    display: block; 
    text-decoration: none; 
    padding: 10px 15px; 
    border: 1px solid transparent;         /*Trick 2*/
    background: transparent;               /*Trick 2*/ 
}
ul li a:hover{
    background: #eee;
}
ul li.active a{ 
    border-radius: 4px 4px 0 0;
    border: 1px solid #ddd; 
    border-bottom: 1px solid transparent; /*Trick 3*/ 
    background: #fff;                     /*Trick 3*/ 
}

jQuery: 
$(function(){
    $('li a').on('click', function(e){
        e.preventDefault(); // to avoid page refresh because a elements have # in href 
        $('li').removeClass('active');
        $(this).parent('li').addClass('active');
    });
});


Demo: http://jsfiddle.net/dipaks2011/o35c8yxt/

Note: The fiddle demo is creating a ghost border on the right side of the tabs which doesn't appear in real HTML page.


1 comment: