Creating Tabs with HTML, CSS & jQuery

In this tutorial, we’re going to look at how to create tabs in HTML, CSS and jQuery. If you get stuck, don’t hesitate to ask me a question.

Tabs are a great way of grouping lots of content into a very small space. Think of tabs like the TARDIS…bigger on the inside. They can be incredibly handy when you have a lot of content that would simply fill up your page with too much information in one go.

You might also like: Creating an Accordion with HTML, CSS & jQuery.

Table of Contents

  1. Skip to the HTML
  2. Skip to the CSS
  3. Skip to the jQuery

1.) The HTML

Completed Code (HTML)

I go into detail on the specifics of the HTML layout below.

<div class="tabs">
	<ul class="tab-links">
		<li class="active"><a href="#tab1">Tab #1</a></li>
		<li><a href="#tab2">Tab #2</a></li>
		<li><a href="#tab3">Tab #3</a></li>
		<li><a href="#tab4">Tab #4</a></li>
	</ul>

	<div class="tab-content">
		<div id="tab1" class="tab active">
			<p>Tab #1 content goes here!</p>
			<p>Donec pulvinar neque sed semper lacinia. Curabitur lacinia ullamcorper nibh; quis imperdiet velit eleifend ac. Donec blandit mauris eget aliquet lacinia! Donec pulvinar massa interdum risus ornare mollis.</p>
		</div>

		<div id="tab2" class="tab">
			<p>Tab #2 content goes here!</p>
			<p>Donec pulvinar neque sed semper lacinia. Curabitur lacinia ullamcorper nibh; quis imperdiet velit eleifend ac. Donec blandit mauris eget aliquet lacinia! Donec pulvinar massa interdum risus ornare mollis. In hac habitasse platea dictumst. Ut euismod tempus hendrerit. Morbi ut adipiscing nisi. Etiam rutrum sodales gravida! Aliquam tellus orci, iaculis vel.</p>
		</div>

		<div id="tab3" class="tab">
			<p>Tab #3 content goes here!</p>
			<p>Donec pulvinar neque sed semper lacinia. Curabitur lacinia ullamcorper nibh; quis imperdiet velit eleifend ac. Donec blandit mauris eget aliquet lacinia! Donec pulvinar massa interdum ri.</p>
		</div>

		<div id="tab4" class="tab">
			<p>Tab #4 content goes here!</p>
			<p>Donec pulvinar neque sed semper lacinia. Curabitur lacinia ullamcorper nibh; quis imperdiet velit eleifend ac. Donec blandit mauris eget aliquet lacinia! Donec pulvinar massa interdum risus ornare mollis. In hac habitasse platea dictumst. Ut euismod tempus hendrerit. Morbi ut adipiscing nisi. Etiam rutrum sodales gravida! Aliquam tellus orci, iaculis vel.</p>
		</div>
	</div>
</div>

Tab Links

Starting off there’s a div with class="tabs". Inside there’s an unordered list, (or an ordered one if you like, it makes no real difference), with class="tab-links". Inside the list items there are anchor links. The first list item is marked as class="active". This indicates where to start the tabs.

Note: When the CSS is all done, the tab link parent with class="active" will be the highlighted one on page load.

<div class="tabs">
	<ul class="tab-links">
		<li class="active"><a href="#tab1">Tab #1</a></li>
		<li><a href="#tab2">Tab #2</a></li>
		<li><a href="#tab3">Tab #3</a></li>
		<li><a href="#tab4">Tab #4</a></li>
	</ul>
</div>

Tab Content

There’s a div with class="tab-content". Inside of that, we have 4 divs, each with class="tab", (this number corresponds to how many tab links there are). The currently visible tab will also need an active class, e.g. class="tab active".

<div class="tab-content">
	<div id="tab1" class="tab active">
		<p>Tab #1 content goes here!</p>
		<p>Donec pulvinar neque sed semper lacinia. Curabitur lacinia ullamcorper nibh; quis imperdiet velit eleifend ac. Donec blandit mauris eget aliquet lacinia! Donec pulvinar massa interdum risus ornare mollis.</p>
	</div>

	<div id="tab2" class="tab">
		<p>Tab #2 content goes here!</p>
		<p>Donec pulvinar neque sed semper lacinia. Curabitur lacinia ullamcorper nibh; quis imperdiet velit eleifend ac. Donec blandit mauris eget aliquet lacinia! Donec pulvinar massa interdum risus ornare mollis. In hac habitasse platea dictumst. Ut euismod tempus hendrerit. Morbi ut adipiscing nisi. Etiam rutrum sodales gravida! Aliquam tellus orci, iaculis vel.</p>
	</div>

	<div id="tab3" class="tab">
		<p>Tab #3 content goes here!</p>
		<p>Donec pulvinar neque sed semper lacinia. Curabitur lacinia ullamcorper nibh; quis imperdiet velit eleifend ac. Donec blandit mauris eget aliquet lacinia! Donec pulvinar massa interdum ri.</p>
	</div>

	<div id="tab4" class="tab">
		<p>Tab #4 content goes here!</p>
		<p>Donec pulvinar neque sed semper lacinia. Curabitur lacinia ullamcorper nibh; quis imperdiet velit eleifend ac. Donec blandit mauris eget aliquet lacinia! Donec pulvinar massa interdum risus ornare mollis. In hac habitasse platea dictumst. Ut euismod tempus hendrerit. Morbi ut adipiscing nisi. Etiam rutrum sodales gravida! Aliquam tellus orci, iaculis vel.</p>
	</div>
</div>

2 The CSS

I’m going to keep it simple with basic CSS (as opposed to an SCSS pre-processor like Sass, Less or Stylus). The bulk of this tutorial is aimed at beginners, so I’m taking that into account.

Completed Code (CSS)

I go into detail on the specifics of the CSS styling below.

/*----- Tabs -----*/
.tabs {
	width:100%;
	display:inline-block;
}

/*----- Tab Links -----*/
/* Clearfix */
	.tab-links:after {
	display:block;
	clear:both;
	content:'';
}

.tab-links li {
	margin:0px 5px;
	float:left;
	list-style:none;
}

.tab-links a {
	padding:9px 15px;
	display:inline-block;
	border-radius:3px 3px 0px 0px;
	background:#7FB5DA;
	font-size:16px;
	font-weight:600;
	color:#4c4c4c;
	transition:all linear 0.15s;
}

.tab-links a:hover {
	background:#a7cce5;
	text-decoration:none;
}

li.active a, li.active a:hover {
	background:#fff;
	color:#4c4c4c;
}

/*----- Content of Tabs -----*/
.tab-content {
	padding:15px;
	border-radius:3px;
	box-shadow:-1px 1px 1px rgba(0,0,0,0.15);
	background:#fff;
}

.tab {
	display:none;
}

.tab.active {
	display:block;
}

Tabs Container

The display:inline-block; adds a type of clearfix while also making it more ‘stable’ than if we used display:block;.

The reason we use a clearfix above yet not here is as follows: display:inline-block; sometimes adds 7px-ish of margin below the affected element with no way of removing it. Sometimes using a minus bottom margin works, but it depends heavily on how your HTML is structured. In this instance it’s fine.

/*----- Tabs -----*/
.tabs {
	width:100%;
	display:inline-block;
}

Tab Link Wrappers

We declare no list-style to stop it appearing as a default list. Then the margin so the links are spaced evenly apart, (using margin:0px 5px; is the same as using margin:0px 5px 0px 5px;).

.tab-links li {
	margin:0px 5px;
	float:left;
	list-style:none;
}

Tab Links

These are all basic styles which you should understand if you’re attempting this tutorial. If you don’t, please find the proper values and the definitions for each on the CSS-Tricks Almanac.

You may be wondering why I’ve used transition:all linear 0.15s; instead of transition:background linear 0.15s;. The reason is simple, in my experience, you have to think ahead. If you don’t then nasty, (sometimes hard to fix), bugs pop-up seemingly out of nowhere. By using background instead of all, we’d be limiting what can be transitioned on the :hover effect. Since this is a tutorial, many of you may want to change the text colour on hover. By using all instead of background that makes it possible.

.tab-links a {
	padding:9px 15px;
	display:inline-block;
	border-radius:3px 3px 0px 0px;
	background:#7FB5DA;
	font-size:16px;
	font-weight:600;
	color:#4c4c4c;
	transition:all linear 0.15s;
}

.tab-links a:hover {
	background:#a7cce5;
	text-decoration:none;
}

li.active a, li.active a:hover {
	background:#fff;
	color:#4c4c4c;
}

Tab Content

This is the background of the tab content section.

/*----- Content of Tabs -----*/
.tab-content {
	padding:15px;
	border-radius:3px;
	box-shadow:-1px 1px 1px rgba(0,0,0,0.15);
	background:#fff;
}

Non-Active/Active Tab Content

We set all tabs to display:none; which hides them. Then we set the active tab to display:block; so only that one will show up. It’s a simple case of using CSS the way it was designed, which was to cascade down. Hence the name, Cascading Stylesheets.

.tab {
	display:none;
}

.tab.active {
	display:block;
}

You might also like: Creating a Dropdown Menu with HTML & CSS


3 The jQuery

Below you can see the completed jQuery code. Keep scrolling for a good explanation of how it all works and what it all means.

Let me clarify something before we start: Everyone has their own way of coding, with jQuery this is mine. Writing it out like this makes it easier for a beginner to grasp, it’s also efficient.

Completed Code (jQuery)

jQuery(document).ready(function() {
	jQuery('.tabs .tab-links a').on('click', function(e) {
		var currentAttrValue = jQuery(this).attr('href');

		// Show/Hide Tabs
		jQuery('.tabs ' + currentAttrValue).show().siblings().hide();

		// Change/remove current tab to active
		jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

		e.preventDefault();
	});
});

Basic Setup

You have to start by checking if the document is ready, for this we use:

jQuery(document).ready(function() {
	// Code Here
});

Next is to check if the user has clicked on a tab, to do that we simply reference every link that happens to be a tab link with .tab-links a.

jQuery('.tab-links a').on('click', function(e) {
	// More Code Here
});

Dynamic Variable

Next, we create a variable called currentAttrValue, (current attribute value), which grabs the href="" of the clicked anchor link.

var currentAttrValue = jQuery(this).attr('href');

Match Anchor Link to Div #ID

We need a way of matching up the .tab-link anchors with .tab sections. We start off by referring to the entire tabs component, with .tabs, then we say “If .tabs has a child with an #id that then matches a .tab-link href="", then they should be linked up”.

Then we say “Show the element with the referenced #id, such as #tab2, then find the other tabs, which are siblings of #tab2, and hide them”.

jQuery('.tabs ' + currentAttrValue).show().siblings().hide();

Giving The Tab Link an Active State

Changing the active state of the tab link is relatively the same as showing/hiding the tab content.

First, we look for jQuery(this), which is the current anchor link being clicked. Then we find it’s parent list item with .parent('li') tag. After that, we give that parent list item a class of .active by using .addClass('active'). Lastly, we find all siblings of that parent list item and remove, if any, classes of .active by using .siblings().removeClass('active').

jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

Prevent Default Anchor Link Behaviour

You may notice that when you click an anchor link with an #id specified instead of an actual URL, it tends to add the #id into the address bar. E.G. http://sebkay.com becomes http://sebkay.com/#id. This can be a massive pain-point for users when trying to click the back button.

To get past that UX problem we use:

e.preventDefault();

This handy little function stops the default action of the clicked element from happening.

Remember when we put that function(e)at the start of our click event? Well, this is where that ties in.


Extra Credit: jQuery Animations

You may not like the way it just jumps to the new tab content without any nice animation of any kind, well here’s some extra credit.

To apply these changes simply replace the below snippet with the other code snippets that follow.

Default

// Show/Hide Tabs
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();

Fade

// Show/Hide Tabs
jQuery('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();

Slide 1

// Show/Hide Tabs
jQuery('.tabs ' + currentAttrValue).siblings().slideUp(400);
jQuery('.tabs ' + currentAttrValue).delay(400).slideDown(400);

Slide 2

// Show/Hide Tabs
jQuery('.tabs ' + currentAttrValue).slideDown(400).siblings().slideUp(400);

Conclusion

If you’re reading this conclusion, (most people, including me, tend to leave after they’ve got the code they were after), then please leave a comment below with any problems or bugs regarding this tutorial. I’m writing this to help people learn and become the best they can be.

You might also like: 21 Must-Have Front End Development Tools.


Comments

Leave a Comment

Comments (561)

Doug

November 9, 2020 at 8:50 pm

Thanks for a workable piece of software. Your explanations of the segments were helpful.

Reply

Kris H.

September 23, 2020 at 2:55 pm

I like your tutorial on creating tabs with jQuery. The one thing I wish is that you had a live demo of it. If there is one, I couldn’t find it. I put a modified copy in Codepen at https://codepen.io/poto228/pen/abNPPvw for viewing.

Reply

KARUHANGA INNOCENT

June 10, 2020 at 10:40 am

for sure thank you for i have atleast got something though iam not yet perfect to the extent but i thank you for being helpfull to the comunity #Be Blessed

Reply

Raihan Sultan

August 2, 2019 at 8:06 pm

Thanks for nice tab demo create

Reply

dixie

May 22, 2019 at 6:42 am

the preventdefault doesn’t prevent the jumping action caused by the url # anchor , how to fix it?

Reply

Umair

November 21, 2018 at 2:55 am

How to create different sections with in a tab with different backgrounds? I am talking about full page tabbed content. Let us say I am creating an about us page which is a tabbed content. This page will have no tabs in itself. User will have to scroll. I want to show About company, another section with mission vision, another part with a map or something or anything. Simply, I want to divide this page into different parts with different backgrounds and styles. I am using html5 and css3.

Reply

Andrew Adutu

October 25, 2018 at 9:06 am

Thanks for sharing your knowledge, indeed it’s great one. My challenges is, the Jquery was not working for me when I connect the html and to my script. But Html and CSS is working perfectly. Am using Ubuntu Gnome 16.04 and with Firefox browser. Please any assistance to help me with to make it work.Thanks.

Reply

BRad

October 8, 2018 at 1:17 pm

Thanks for the help mate

Reply

Calley

October 5, 2018 at 1:19 am

Thank you! This was exactly what I needed.

Reply

Thank you

July 25, 2018 at 4:07 pm

Thank you, very well explained and simple 🙂

Reply

jutt

June 14, 2018 at 3:40 pm

Thanks thanks a million 🙂 it worked really fine, i had my head scratched up because of this and you seemed to do a magic trick.

Reply

stefan

February 16, 2018 at 7:02 pm

I am interested in your tutorial on “Creating Tabs with HTML, CSS & jQuery”. But, I wonder, does the codes (html, css, and jQuesry) can be written in one .html file?

Reply

stefan

February 16, 2018 at 6:51 pm

ummm.. the tabs are not functioning on any of the web browsers and i’m having a problem with that.. so could you please help me?

Reply

jacob

February 9, 2018 at 2:32 pm

how would i make the tabs equal to 50% of the container each, my goal is to make only 2 tabs but static at the top.

Reply

Marc

November 16, 2017 at 8:27 pm

Hi, this code is sleek and tight. But it only works in Chrome. In Edge and Firefox, everything styles and positions fine, but the clicked-on tabs don’t switch to the active state and the content doesn’t display.

Thanks for any help!

Reply

seul

October 25, 2017 at 7:19 am

How can I make the tabs open on page reload? For example, I have a form that posts from the second tab, but ofc when I reload the page it goes to the first tab because the click function has not be initialized. What is the best solution for this!?

Reply

Elizabeth Smith

October 8, 2017 at 10:11 pm

I’m sure this code is wrong. I don’t know what’s wrong with this code.

&lt;div class=&quot;tabs&quot;&gt;<br />
    &lt;ul class=&quot;tab-links&quot;&gt;<br />
        &lt;li class=&quot;active&quot;&gt;&lt;a href=&quot;#tab1&quot;&gt;Tab #1&lt;/a&gt;&lt;/li&gt;<br />
        &lt;li&gt;&lt;a href=&quot;#tab2&quot;&gt;Tab #2&lt;/a&gt;&lt;/li&gt;<br />
        &lt;li&gt;&lt;a href=&quot;#tab3&quot;&gt;Tab #3&lt;/a&gt;&lt;/li&gt;<br />
        &lt;li&gt;&lt;a href=&quot;#tab4&quot;&gt;Tab #4&lt;/a&gt;&lt;/li&gt;<br />
    &lt;/ul&gt;</p>
<p>    &lt;div class=&quot;tab-content&quot;&gt;<br />
        &lt;div id=&quot;tab1&quot; class=&quot;tab active&quot;&gt;<br />
            &lt;p&gt;Tab #1 &lt;/p&gt;</p>
<p>        &lt;/div&gt;</p>
<p>        &lt;div id=&quot;tab2&quot; class=&quot;tab&quot;&gt;<br />
            &lt;p&gt;Tab #2 &lt;/p&gt;</p>
<p>        &lt;/div&gt;</p>
<p>        &lt;div id=&quot;tab3&quot; class=&quot;tab&quot;&gt;<br />
            &lt;p&gt;Tab #3&lt;/p&gt;</p>
<p>        &lt;/div&gt;</p>
<p>        &lt;div id=&quot;tab4&quot; class=&quot;tab&quot;&gt;<br />
            &lt;p&gt;Tab #4 &lt;/p&gt;</p>
<p>        &lt;/div&gt;<br />
    &lt;/div&gt;<br />
/*—– Tabs —–*/<br />
.tabs {<br />
    width:100%;<br />
    display:inline;<br />
}</p>
<p>    /*—– Tab Links —–*/<br />
    /* Clearfix */<br />
    .tab-links:after {<br />
        display:;<br />
        clear:both;<br />
        content:”;<br />
    }</p>
<p>    .tab-links li {<br />
        margin:0px 5px;<br />
        float:left;<br />
        list-style:none;<br />
    }</p>
<p>        .tab-links a {<br />
            padding:9px 15px;<br />
            display:inline-block;<br />
            border-radius:3px 3px 0px 0px;<br />
            background:#7FB5DA;<br />
            font-size:16px;<br />
            font-weight:600;<br />
            color:#4c4c4c;<br />
            transition:all linear 0.15s;<br />
        }</p>
<p>        .tab-links a:hover {<br />
            background:#a7cce5;<br />
            text-decoration:none;<br />
        }</p>
<p>    li.active a, li.active a:hover {<br />
        background:#fff;<br />
        color:#4c4c4c;<br />
    }</p>
<p>    /*—– Content of Tabs —–*/<br />
    .tab-content {<br />
        padding:15px;<br />
        border-radius:3px;<br />
        box-shadow:-1px 1px 1px rgba(0,0,0,0.15);<br />
        background:#fff;<br />
    }</p>
<p>        .tab {<br />
            display:.addClass(‘active’);<br />
        }</p>
<p>        .tab.active {<br />
            display:;<br />
        }<br />
&lt;/div&gt;<br />

Reply

PerOgPål

October 7, 2017 at 11:21 pm

Thanks for doing this, exactly what I needed. One problem: Tab1 is always highlighted. The content changes, but the tab itself doesn’t transition. What could be the reason for this?

Reply

Michael

September 2, 2017 at 3:20 pm

Hi!
Thanks for your code, works perfectly 🙂
One Question: the tabs align left in your example, how can i center them?

Thanks in advance
Michael

Reply

mrunalini

August 30, 2017 at 2:21 pm

how to create form tabs?

Reply

Inspirational Newsletter


Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.

No spam. You can unsubscribe at any time.