How to Create: Tabbed Image Gallery

Learn how to create a tabbed image gallery using CSS and JavaScript.

Tabbed Image Gallery

Click on the image to expand:

Wuhan
Beijing
Shenzhen
Hangzhou
×

Try It Yourself

Create a Tab Gallery

Step 1 - Add HTML:

<!-- 网格:四列 -->
<div class="row">
  <div class="column">
    <img src="img_nature.jpg" alt="Nature" onclick="myFunction(this);">
  </div>
  <div class="column">
    <img src="img_snow.jpg" alt="Snow" onclick="myFunction(this);">
  </div>
  <div class="column">
    <img src="img_mountains.jpg" alt="Mountains" onclick="myFunction(this);">
  </div>
  <div class="column">
    <img src="img_lights.jpg" alt="Lights" onclick="myFunction(this);">
  </div>
</div>
<!-- 展开的图像容器 -->
<div class="container">
  <!-- 关闭图像 -->
  <span onclick="this.parentElement.style.display='none'" class="closebtn">×</span>
  <!-- 扩展图像 -->
  <img id="expandedImg" style="width:100%">
  <!-- 图像文本 -->
  <div id="imgtext"></div>
</div>

Use images to expand specific images. After clicking the image in the column, the image will be displayed in the container below the column.

Second step - Add CSS:

Create four columns and set image styles:

/* Grid: four equal columns side by side */
.column {
  float: left;
  width: 25%;
  padding: 10px;
}
/* Set the style of the images inside the grid */
.column img {
  opacity: 0.8;
  cursor: pointer;
}
.column img:hover {
  opacity: 1;
}
/* Clear the float after the column */
.row:after {
  content: "";
  display: table;
  clear: both;
}
/* The container of the expanded image (needs positioning to place the close button and text) */
.container {
  position: relative;
  display: none;
}
/* The text of the expanded image */
#imgtext {
  position: absolute;
  bottom: 15px;
  left: 15px;
  color: white;
  font-size: 20px;
}
/* The closable button inside the image */
.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}

Third step - Add JavaScript:

function myFunction(imgs) {
  // Get the expanded image
  var expandImg = document.getElementById("expandedImg");
  // Get the image text
  var imgText = document.getElementById("imgtext");
  // Use the same src as the image clicked from the grid in the expanded image
  expandImg.src = imgs.src;
  // Use the value of the alt attribute of the clickable image as the text inside the expanded image
  imgText.innerHTML = imgs.alt;
  // Show the container element (hidden with CSS)
  expandImg.parentElement.style.display = "block";
}

Try It Yourself