How to Create: Tab Title

Learn how to create tab titles using CSS and JavaScript.

Tab Title

Please click the "city" button to display the corresponding title:

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

Oslo

Oslo is the capital of Norway.

Try It Yourself

Create a toggleable tab title

Step 1 - Add HTML:

<div id="London" class="tabcontent">
  <h1>London</h1>
  <p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
  <h1>Paris</h1>
  <p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
  <h1>Tokyo</h1>
  <p>Tokyo is the capital of Japan.</p>
</div>
<div id="Oslo" class="tabcontent">
  <h1>Oslo</h1>
  <p>Oslo is the capital of Norway.</p>
</div>
<button class="tablink" onclick="openCity('London', this, 'red')" id="defaultOpen">London</button>
<button class="tablink" onclick="openCity('Paris', this, 'green')">Paris</button>
<button class="tablink" onclick="openCity('Tokyo', this, 'blue')">Tokyo</button>
<button class="tablink" onclick="openCity('Oslo', this, 'orange')">Oslo</button>
Create buttons to open specific tab content. All <div> elements with class="tabcontent" are hidden by default (with CSS & JS). When the user clicks on a button - it will open the tab content that "matches" this button.

Step 2 - Add CSS:

Set the style of the button and tab content:

/* Set the style of the tab button */
.tablink {
  background-color: #555;
  color: white;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  font-size: 17px;
  width: 25%;
}
/* Change the background color of the button when hovering */
.tablink:hover {
  background-color: #777;
}
/* Set the default style for tab content */
.tabcontent {
  color: white;
  display: none;
  padding: 50px;
  text-align: center;
}
/* Set the style for each tab content separately */
#London {background-color:red;}
#Paris {background-color:green;}
#Tokyo {background-color:blue;}
#Oslo {background-color:orange;}

Third step - Add JavaScript:

function openCity(cityName, elmnt, color) {
  // Default hide all elements with class="tabcontent"
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  // Remove the background color from all tab links/buttons
  tablinks = document.getElementsByClassName("tablink");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].style.backgroundColor = "";
  }
  // Display the specific tab content
  document.getElementById(cityName).style.display = "block";
  // Add a specific color to the button used to open the tab content
  elmnt.style.backgroundColor = color;
}
// Get the element with id="defaultOpen" and click it
document.getElementById("defaultOpen").click();

Try It Yourself

Related Pages

Tutorial:How to Create Tab