How to Create Tab Headers with CSS and JavaScript

Creating tab headers is an essential part of creating dynamic user interfaces.

The tab headers provide a clean and organized way to display different sections of content, making it easier for the users to navigate your website or application.

In this tutorial, we will explore how to create tab headers with CSS and JavaScript.


HTML Structure

First, let’s define the HTML structure that we need to create the tab headers.

We will use an unordered list to define the tab headers and a series of div elements to display the content.

<ul class="tab-header">
  <li class="active">Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
</ul>

<div class="tab-content">
  <div class="active">Tab 1 Content</div>
  <div>Tab 2 Content</div>
  <div>Tab 3 Content</div>
</div>

CSS Styles

Next, let’s style the tab headers and content with CSS.

We will hide all the content by default and only display the content of the active tab.

.tab-header {
display: flex;
list-style: none;
margin: 0;
padding: 0;
}

.tab-header li {
cursor: pointer;
flex-grow: 1;
text-align: center;
border: 1px solid gray;
padding: 10px;
}

.tab-header .active {
background-color: lightgray;
}

.tab-content div {
display: none;
}

.tab-content .active {
display: block;
}

JavaScript Functionality

Finally, let’s add the JavaScript functionality that will allow us to switch between the tabs.

We will add an event listener to each tab header, and when a user clicks on a tab header, we will update the active class on both the header and content.

const tabHeaders = document.querySelectorAll(".tab-header li");
const tabContents = document.querySelectorAll(".tab-content div");

tabHeaders.forEach(header => {
header.addEventListener("click", function() {
const activeHeader = document.querySelector(".tab-header .active");
const activeContent = document.querySelector(".tab-content .active");
activeHeader.classList.remove("active");
activeContent.classList.remove("active");
header.classList.add("active");
tabContents[Array.from(tabHeaders).indexOf(header)].classList.add("active");
});
});

Conclusion

In this article, we have explored how to create tab headers with CSS and JavaScript.

By combining HTML, CSS, and JavaScript, we have created a dynamic and user-friendly interface that allows users to easily switch between different sections of content.

I hope this article was helpful, and you can use this as a starting point for your next project.