Home / design

Tabs on HTML page

If you want to create Toggleable Tabs on your web-page, you can do it with HTML, CSS and JavaScript.

HTML-code

<!-- Tab links -->
<div class="tab">
  <button class="tablinks" onclick="openTab(event,'Tab1')" id="defaultOpen">First tab</button>
  <button class="tablinks" onclick="openTab(event,'Tab2')">Second tab</button>
  <button class="tablinks" onclick="openTab(event,'Tab3')">and so one</button>
</div>

<!-- Tab content -->
<div id="Tab1" class="tabcontent">
  <h3>First tab</h3>
  <p>Body of the tab 1.</p>
</div>

<div id="Tab2" class="tabcontent">
  <h3>Second tab</h3>
  <p>Body of the tab 2.</p>
</div>

<div id="Tab3" class="tabcontent">
  <h3>and so one</h3>
  <p>Body of the tab.</p>
</div>

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.

Add CSS:

/* Style the tab */
.tab
{
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons that are used to open the tab content */
.tab button
{
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
}

/* Change background color of buttons on hover */
.tab button:hover { background-color: #ddd; }

/* Create an active/current tablink class */
.tab button.active { background-color: #ccc; }

/* Style the tab content */
.tabcontent
{
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

Add JavaScript:

function openTab(evt, tabName)
{
    // Declare all variables
    var i, tabcontent, tablinks;

    // Get all elements with class="tabcontent" and hide them
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++)
    {
        tabcontent[i].style.display = "none";
    }

    // Get all elements with class="tablinks" and remove the class "active"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++)
    {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Show the current tab, and add an "active" class to the button that opened the tab
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}
//remove this line and all tabs will be closed on page loading
document.getElementById("defaultOpen").click();

 

Example

First tab

Body of the tab 1.

Second tab

Body of the tab 2.

and so one

Body of the tab.

 

TOP