Pure CSS Tab Panel


CSS only tab panel implementation. The tab panel here is similar to Bootstrap tab, but no JavaScript required. Click the following tabs to see the demo.

My home
My profile

The basic technique is the same as pure CSS toggle HTML element [7]. We need:

  • Visible HTML label elements, which is the navigation tabs.
  • Invisible HTML input radio elements, referenced by the label elements. The value of name attribute of these elements must be the same.
  • Tab contents, invisible in the beginning.

When users click on the visible label elements, the corresponding input radio element is checked. We use CSS3 :checked selector to select corresponding tab content, and make the selected tab content visible.

The complete source code is as follows:

HTML:

<!-- Nav tabs -->
<input type="radio" id="tab-home" name="nav-tab">
<input type="radio" id="tab-profile" name="nav-tab">
<ul class="nav-tabs">
  <li><label for="tab-home">Home</label></li>
  <li><label for="tab-profile">Profile</label></li>
</ul>

<!-- Tab panes -->
<div class="tab-content">
  <div class="tab-pane content-home">My home</div>
  <div class="tab-pane content-profile">My profile</div>
</div>

CSS:

.nav-tabs {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
  border-bottom: 1px solid #ddd;
  list-style: none;
}
.nav-tabs > li {
  margin-bottom: 1px;
  margin-right: 1rem;
  line-height: 2rem;
  cursor: pointer;
}
.tab-pane {
  padding: 1rem;
  display: none;
}

input[type="radio"] {
  display: none;
}

/* the magic */
#tab-home:checked ~ .tab-content > .content-home,
#tab-profile:checked ~ .tab-content > .content-profile {
  display: block;
}
  • The first two rules use flexbox to align the tabs in one row.
  • The third and fourth rules hide the tab content and input radio box.
  • The magic is in last rule. We use :checked and general sibling selector (~) to make the user-selected tab content visible.

Tested on:

  • Chromium 58.0.3029.110 on Ubuntu 17.04 (64-bit)

References:

[1]有趣的CSS题目(8):纯CSS的导航栏Tab切换方案 - WEB前端 - 伯乐在线
[2]有趣的CSS题目(10):结构性伪类选择器 - WEB前端 - 伯乐在线
[3]巧用 CSS 的 :target 选择器,打造没有 JS 的 UI 效果 - WEB前端 - 伯乐在线
[4]
[5]CSS3 :target Selector
[6]
[7]Pure CSS Toggle (Show/Hide) HTML Element