Table Of Contents
show
If you’re a WordPress developer building custom WordPress websites, you may find yourself in a situation where you need to create tabs. Here is a simple way to do this with HTML, CSS, javascript, and jQuery.
1. HTML
<div class="tabs">
<ul class="tab-header">
<li class="active tab-header-item">
<a href="#tab-1">Tab 1</a>
</li>
<li class="tab-header-item">
<a href="#tab-2">Tab 2</a>
</li>
</ul>
<div class="tab-content active" id="tab-1">
Tab 1 content
</div>
<div class="tab-content" id="tab-2">
Tab 2 content
</div>
</div>
2. CSS
.tab-header {
list-style: none;
display: flex;
padding-left: 0;
margin: 0;
}
.tab-header a {
padding: 10px 20px;
text-decoration: none;
border: 1px solid #ddd;
border-bottom: 0;
color: #000;
display: block;
}
.tab-header li a:hover,
.tab-header li.active a {
background-color: #00aaff;
color: #fff;
}
.tab-header li:not(:last-of-type) a {
border-right: 0;
}
.tab-content {
display: none;
border: 1px solid #ddd;
padding: 20px;
}
.tab-content.active {
display: block;
}
3. JavaScript
(function($) {
$(function() {
$('.tab-header a').click(function(e) {
e.preventDefault();
var $el = $(e.target);
var $target = $($el.attr('href'));
var $parent = $el.closest('.tabs');
$parent.find('.tab-content').removeClass('active');
$parent.find('.tab-content').removeClass('active');
$el.closest('ul').find('.tab-header-item').removeClass('active');
$el.closest('li').addClass('active');
$target.addClass('active');
});
});
}(jQuery));
Final Result
Here is the final result in action
See the Pen JavaScript Tabs by Andriy (@angay9) on CodePen.
Conclusion
That’s it, that’s how you can easily create a tabs widget for your site.