LoginSignup
3
0

More than 3 years have passed since last update.

CSSのみでタブとタブコンテンツの表示・非表示を切り替える

Posted at

HTMLコーダーさんのJSを使わないタブ切り替えが、シンプルな実装で素晴らしかったので忘備録的にメモ。

概要

  • タブは『インプットボックス』+『ラベル』を使用
  • コンテンツエリアは常時非表示にしておく
  • コンテンツエリアは選択されたときのみ表示する

サンプルコード

動かしてないので不具合あるかもですが、こんな感じでした。


<div class="tabs">
  <!-- タブ -->
  <input id="tab_1" type="radio" name="tab" checked="">
  <label class="tab_label" for="tab_1">月別</label>
  <input id="tab_2" type="radio" name="tab">
  <label class="tab_label" for="tab_2">週間別</label>
  <input id="tab_3" type="radio" name="tab">
  <label class="tab_label" for="tab_3">曜日別</label>

  <div class="tab_content" id="content_1">コンテンツ1</div>
  <div class="tab_content" id="content_2">コンテンツ2</div>
  <div class="tab_content" id="content_3">コンテンツ3</div>
</div>

input[name="tab"] {
    display: none;
}

.tabs {
  width: 100%;
}

.tab_label {
  border-top: 1px solid #999999;
  border-bottom: 1px solid #999999;
}

.tabs input:checked + .tab_label {
  border-bottom: 2px solid #55C501;
}

#tab_1:checked ~ #content_1,
#tab_2:checked ~ #content_2,
#tab_3:checked ~ #content_3 {
  display: block;
}

.tab_content {
  display: none;
}
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0