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: 
1
2
3
4
5
6
7
<ul>
  <li class="active"><a href="">Tab 1</a></li>
  <li><a href="">Tab 2</a></li>
  <li><a href="">Tab 3</a></li>
  <li><a href="">Tab 4</a></li>
  <li><a href="">Tab 5</a></li>
</ul>
CSS: 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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: 
1
2
3
4
5
6
7
$(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: