Tabbed DIV content with CSS and jQuery

This tutorial will show you how to turn your unordered lists into tabbed content using css and jQuery.

Preview

tabbed-content-using-css-and-jquery

HTML

There is going to be two unordered lists. One for the tab links, and the other for their content.

  1.  
  2. <div id="tabs">
  3.   <ul id="tab-links">
  4.     <li id="tab-link-1" class="selected">Tab 1</li>
  5.     <li id="tab-link-2">Tab 2</li>
  6.     <li id="tab-link-3">Tab 3</li>
  7.   </ul>
  8.  
  9.   <ul id="tab-content">
  10.     <li id="tab-content-1">content for tab-1 here</li>
  11.     <li id="tab-content-2">tab-2 here</li>
  12.     <li id="tab-content-3">third and last one, tab-3</li>
  13.   </ul>
  14. </div>

CSS

First of all, we define the width of our container and clear the floats.

  1. #tabs {
  2.   width: 300px;
  3. }
  4.  
  5. #tabs ul {
  6.   clear: both;
  7. }

Now we turn our first unordered list into a horizontal menu.

  1. #tab-links {
  2.   list-style: none;
  3.   padding: 0px;
  4.   margin: 0px;
  5. }
  6.  
  7. #tab-links li {
  8.   float: left;
  9.   padding: 10px;
  10.   color: #3b5d14;
  11.   background-color: #b2d281;
  12.   border-right: 1px solid #fff;
  13.   font-size: 18px;
  14. }
  15.  
  16. #tab-links li.selected,
  17. #tab-content {
  18.   color: #fff;
  19.   background-color: #90b557;
  20. }

Since we want our content to be available in tabs, it is necessary to hide all the <li> elements except for the first one.

  1. #tab-content {
  2.   padding: 5px;
  3.   margin: 0px;
  4.   list-style: none;
  5.   font-size: 12px;
  6. }
  7.  
  8. #tab-content-2,
  9. #tab-content-3 {
  10.   display: none;
  11. }

JavaScript (jQuery)

Make sure that you add jQuery library to your document first. And then add this few lines of javascript inside your HEAD tag.

  1. $(document).ready(function() {
  2.  
  3.     // tab 1
  4.     $('#tab-link-1').click(function() {
  5.         $('#tab-content-1').show();
  6.         $('#tab-content-2, #tab-content-3').hide();
  7.        
  8.         $(this).attr({class : "selected"});
  9.         $('#tab-link-2, #tab-link-3').attr({class : ""});
  10.     });
  11.    
  12.    
  13.     // tab 2
  14.     $('#tab-link-2').click(function() {
  15.         $('#tab-content-2').show();
  16.         $('#tab-content-1, #tab-content-3').hide();
  17.        
  18.         $(this).attr({class : "selected"});
  19.         $('#tab-link-1, #tab-link-3').attr({class : ""});
  20.     });
  21.    
  22.  
  23.     // tab 3
  24.     $('#tab-link-3').click(function() {
  25.         $('#tab-content-3').show();
  26.         $('#tab-content-1, #tab-content-2').hide();
  27.        
  28.         $(this).attr({class : "selected"});
  29.         $('#tab-link-1, #tab-link-2').attr({class : ""});
  30.     });
  31.    
  32. });
Share: