Create HTML Tabs Using CSS and JavaScript

Creating HTML tabs for your web pages is actually fairly easy to do. It requires a mostly HTML and CSS, and a little bit of jQuery to help to switch between tabs. Tabs are perfect to use when you want to present a lot of information on one page in an organized way.

To start, you’ll need to get your HTML set up. The tabs themselves will be <li> elements, while the tab content will be made up of divs.

Join us in our newest publication:

<div class=”tabs”>
<ul class=”tab-links”>
<li class=”active”><a href=”#tab1″>Pizza</a></li>
<li><a href=”#tab2″>Ice Cream</a></li>
<li><a href=”#tab3″>Burgers</a></li>
<li><a href=”#tab4″>Burritos</a></li>
</ul>

<div class=”tab-content”>
<div id=”tab1″ class=”tab active”>
<p>PIZZA</p>
</div>

<div id=”tab2″ class=”tab”>
<p>ICE CREAM</p>
</div>

<div id=”tab3″ class=”tab”>
<p>BURGERS</p>
</div>

<div id=”tab4″ class=”tab”>
<p>BURRITOS</p>
</div>
</div>

Your styling should then look something like this:

  1. .tabs {
  2. width:60%;
  3. display:inline-block;
  4. }
  5.  
  6. .tab-links{
  7. margin-bottom: 0;
  8. margin-left: 0;
  9. }
  10. .tab-links:after {
  11. display:block;
  12. clear:both;
  13. content:'';
  14. }
  15. .tab-links li {
  16. margin:0px 5px;
  17. float:left;
  18. list-style:none;
  19. }
  20.  
  21. .tab-links a {
  22. padding:9px 15px;
  23. display:inline-block;
  24. border-radius:3px 3px 0px 0px;
  25. background:#e34a3e;
  26. font-size:16px
  27. font-weight:600;
  28. color:#444;
  29. transition:all linear 0.15s;
  30. }
  31.  
  32. .tab-links a:hover {
  33. background:#f67f76;
  34. text-decoration:none;
  35. }
  36.  
  37. li.active a, li.active a:hover {
  38. background:#fff;
  39. color:#4c4c4c;
  40. }
  41.  
  42. .tab-content {
  43. padding:15px;
  44. border-radius:3px;
  45. box-shadow:-1px 1px 1px rgba(0,0,0,0.15);
  46. background:#fff;
  47. }
  48. .tab {
  49. display:none;
  50. }
  51.  
  52. .tab.active {
  53. display:block;
  54. }

You may notice that not much CSS manipulation at all is required to get the tabs to look like tabs. In terms of styling choices, you can decide to style your tabs however you look. Here’s what ours look like:

Screen Shot 2016-11-07 at 1.16.57 PM

In order to get the tabs to work like tabs, however, you’ll need to add a little jQuery:

javascript

  1. jQuery(document).ready(function() {
  2. jQuery('.tabs .tab-links a').on('click', function(e) {
  3. var currentAttrValue = jQuery(this).attr('href');
  4.  
  5. jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
  6.  
  7. jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
  8.  
  9. e.preventDefault();
  10. });
  11. });

The .show() and .hide() methods make it possible for one tab to be active (shown) while the rest are hidden. Play around with the code and customize it to your liking!

Screen Shot 2016-11-07 at 1.17.03 PM

Share and Enjoy !

0Shares
0 0