How to Create Tabs with CSS and JavaScript

Tabs are an essential element of modern websites, allowing users to switch between different sections of content with ease.

With CSS and JavaScript, it’s easy to create custom tabs that look and work exactly as you need them to.

In this tutorial, we’ll show you how to create tabs using CSS and JavaScript, with code examples to help you get started.


HTML Markup for Tabs

The first step in creating tabs is to write the HTML markup.

To do this, we’ll use an unordered list to define the tabs, with each tab being represented by a list item.

We’ll also use an anchor tag within each list item to provide a clickable area for the user to activate the tab.

Here’s an example of the HTML markup for tabs:

<ul class="tabs">
  <li class="tab">
    <a href="#tab1">Tab 1</a>
  </li>
  <li class="tab">
    <a href="#tab2">Tab 2</a>
  </li>
  <li class="tab">
    <a href="#tab3">Tab 3</a>
  </li>
</ul>

<div class="tab-content">
  <div id="tab1">
    Tab 1 Content
  </div>
  <div id="tab2">
    Tab 2 Content
  </div>
  <div id="tab3">
    Tab 3 Content
  </div>
</div>

CSS Styles for Tabs

Once the HTML markup is in place, we can start styling the tabs with CSS. To give the tabs a visual appearance, we’ll use CSS to style the unordered list and list items.

We’ll also use CSS to hide the tab content by default and to show it when a particular tab is active.

Here’s an example of the CSS styles for tabs:

.tabs {
  list-style: none;
  display: flex;
}

.tab {
  margin-right: 10px;
}

.tab a {
  padding: 10px;
  display: block;
  text-decoration: none;
}

.tab-content {
  display: none;
}

#tab1:target, #tab2:target, #tab3:target {
  display: block;
}

JavaScript for Tabs

While CSS is great for styling tabs, it can’t handle the interactivity aspect. For that, we’ll need to use JavaScript.

The JavaScript code will be responsible for showing the active tab and hiding the other tabs when the user clicks on a tab.

Here’s an example of the JavaScript code for tabs:

var tabs = document.querySelectorAll('.tab');

for (var i = 0; i < tabs.length; i++) {
  tabs[i].addEventListener('click', function(e) {
    e.preventDefault();
    var tabId = this.querySelector('a').getAttribute('href');
    document.querySelector('.tab-content').style.display = 'none';
    document.querySelector(tabId).style.display = 'block';
  });
}


Final Thoughts

With HTML, CSS, and JavaScript, creating tabs is a breeze.