#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

How to create tabs using CSS (no JavaScript required)

Last modified September 27th 2022 | GitHub Source Code [GitHub] | #css

In this tutorial we’ll be creating a tab component using CSS with no JavaScript required. Tabs are great for creating an organised user interface by providing a way to quickly view chunks of content without having to scroll the browser.

Let’s get started with the HTML required:

<ul class="tabs">
  <li>
    <input id="tab1" type="radio" name="tabs" checked />
    <label for="tab1">Description</label>
    <div id="tab-panel1" class="tab-panel">
      <p>This is the content for the description panel.</p>
    </div>
  </li>
  <li>
    <input id="tab2" type="radio" name="tabs" />
    <label for="tab2">Specifications</label>
    <div id="tab-panel2" class="tab-panel">
      <p>Specifications content can go here.</p>
    </div>
  </li>  
  <li>
    <input id="tab3" type="radio" name="tabs" />
    <label for="tab3">Reviews</label>
    <div id="tab-panel3" class="tab-panel">
      <p>Here we can display some reviews from our customers.</p>
    </div>
  </li>     
</ul>Code language: HTML, XML (xml)

You’ll have noticed we’re using a radio input here, as you’ll see later in the tutorial this allows us to detect and style the active tab and panel using the :checked selector. The radio inputs will be hidden with CSS because when a label is clicked its corresponding radio is becomes checked, this way we can style the labels to look like buttons.

Now for the CSS starting with the general layout:

.tabs {
  list-style: none; 
  position: relative; 
  margin: 0;
  padding: 0;
  width: 100%;  
  font-family: sans-serif
}
.tabs li {
  display: inline-block;
}
.tabs input[type="radio"] {
  display: none;
}
.tabs label {
  display: block;
  cursor: pointer;
  padding: 10px 15px;
  border: 2px solid black;
  border-bottom: 0;
  border-radius: 3px 3px 0 0;
}
.tabs .tab-panel {  
  display: none;
  overflow: hidden;
  width: 100%;  
  position: absolute;
  left: 0;
  border-top: 2px solid black;
}Code language: CSS (css)

And finally the CSS that will make the tabs function:

.tabs [id^="tab"]:checked + label {   
  background-color: black;
  color: #fff;
}
.tabs [id^="tab"]:checked ~ [id^="tab-panel"] {
  display: block;
}Code language: CSS (css)

Let’s take a closer look at some of the CSS used here:

  • .tabs [id^="tab"]:checked + label – selects the label of a checked radio input with an id prefixed by tab.
  • .tabs [id^="tab"]:checked ~ [id^="tab-panel"] – selects any element with an id prefixed by tab-panel that follows (~) any checked element with an id prefixed by tab.

That’s all for this tutorial. You should now have a functioning tabbed content component that you can easily drop into your next web project. If you found this tutorial interesting be sure to check out some of our other CSS tutorials.

Related Posts

#AD Shop Web Developer T-Shirts