Creating Simple Tabbed Interface with Pure CSS

Category: CSS & CSS3 | June 23, 2015
Author:howar31
Views Total:4,327 views
Official Page:Go to website
Last Update:June 23, 2015
License:MIT

Preview:

Creating Simple Tabbed Interface with Pure CSS

Description:

A pure CSS approach to building a tabs component that makes uses of CSS :target Pseudo-class to toggle the visible of tabbed panels. Without the need of using radio or checkbox elements.

How to use it:

Build the html structure for the tabs component with 3 tabbed panels.

<article class="tabs">
  <section id="tab2">
    <h2><a href="#tab2">Tab 2</a></h2>
    <div class="tab-content">Panel 2</div>
  </section>
  <section id="tab3">
    <h2><a href="#tab3">Tab 3</a></h2>
    <div class="tab-content">Panel 3</div>
  </section>
  <section id="tab3">
    <h2><a href="#tab1">Tab 1</a></h2>
    <div class="tab-content">Panel 1</div>
  </section>
</article>

The basic CSS to style the tabs component.

article.tabs {
  position: relative;
  display: block;
  width: 40em;
  height: 15em;
  margin: 2em auto;
}

article.tabs section {
  position: absolute;
  display: block;
  top: 1.8em;
  left: 0;
  right: 0;
  height: 12em;
  padding: 10px 20px;
  background-color: #ddd;
  border-radius: 5px;
  box-shadow: 0 3px 3px rgba(0,0,0,0.1);
  z-index: 0;
  color: black;
}

article.tabs section .tab-content { display: none; }

article.tabs section:last-child {
  z-index: 1;
  color: #333;
  background-color: #fff;
}

article.tabs section:last-child .tab-content { display: block; }

article.tabs section h2 {
  position: absolute;
  font-size: 1em;
  font-weight: normal;
  width: 120px;
  height: 1.8em;
  top: -1.8em;
  left: 10px;
  padding: 0;
  margin: 0;
  color: #999;
  background-color: #ddd;
  border-radius: 5px 5px 0 0;
}

article.tabs section:last-child h2 {
  color: #333;
  background-color: #fff;
}

article.tabs section:nth-child(1) h2 { left: 132px; }

article.tabs section:nth-child(2) h2 { left: 254px; }

article.tabs section h2 a {
  display: block;
  width: 100%;
  line-height: 1.8em;
  text-align: center;
  text-decoration: none;
  color: inherit;
  outline: 0 none;
}

article.tabs section:target, article.tabs section:target h2 {
  color: #333;
  background-color: #fff;
  z-index: 2;
}

The CSS trick to hide / display tabbed panels using :target Pseudo-class.

article.tabs section:target .tab-content { display: block; }

article.tabs section:target ~ section:last-child h2 {
  color: #999;
  background-color: #ddd;
}

article.tabs section:target ~ section:last-child .tab-content { display: none; }

You Might Be Interested In:


Leave a Reply