How to Create a Tabbed Image Gallery With CSS and JavaScript

Tabbed image galleries are an effective way to present multiple images in a compact space.

They are often used on portfolio and product websites to showcase images in a clean and organized manner.

In this tutorial, we will explore how to create a tabbed image gallery with CSS and JavaScript.


HTML Structure

The first step in creating our tabbed image gallery is to build the HTML structure.

We will start by creating a container that will hold the tabs and images.

<div class="tab-container">
  <div class="tab-menu">
    <div class="tab active" data-tab="tab1">Tab 1</div>
    <div class="tab" data-tab="tab2">Tab 2</div>
    <div class="tab" data-tab="tab3">Tab 3</div>
  </div>
  <div class="tab-content">
    <div class="tab-item active" id="tab1">
      <img src="image1.jpg" alt="Image 1">
    </div>
    <div class="tab-item" id="tab2">
      <img src="image2.jpg" alt="Image 2">
    </div>
    <div class="tab-item" id="tab3">
      <img src="image3.jpg" alt="Image 3">
    </div>
  </div>
</div>

CSS Styles

Once we have the HTML structure in place, the next step is to add some styles to make it look visually appealing.

.tab-container {
width: 500px;
margin: 0 auto;
}

.tab-menu {
display: flex;
justify-content: space-between;
background-color: #f2f2f2;
}

.tab {
padding: 10px 20px;
cursor: pointer;
}

.tab.active {
background-color: #ddd;
}

.tab-content {
display: flex;
}

.tab-item {
width: 100%;
display: none;
}

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

JavaScript Functionality

Finally, we will add some JavaScript to make the tabs functional.

The JavaScript code will add and remove the “active” class based on which tab is clicked.

const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-item');

tabs.forEach(tab => {
  tab.addEventListener('click', function() {
    const tabData = this.dataset.tab;
    const tabContent = document.querySelector(`#${tabData}`);
    
    tabs.forEach(tab => {
      tab.classList.remove('active');
    });
    tabContents.forEach(tabContent => {
      tabContent.classList.remove('active');
    });
    
    this.classList.add('active');
    tabContent.classList.add('active');
  });
});

Conclusion

In this tutorial, we learned how to create a tabbed image gallery with CSS and JavaScript.