タブUI

タブUIとは、複数のコンテンツをひとつのエリアにまとめ、クリックで切り替えて表示できるインターフェースです。限られたスペースに多くの情報を表示できるのが利点です。

タブ1の内容です。
タブ2の内容です。
タブ3の内容です。

解説

このタブUIは、ボタンをクリックすることで、JavaScriptが該当の要素に `.is-active` クラスを付与し、CSSで `opacity: 0` や `height: 0`、`visibility: hidden` を指定して非表示にしていた要素を、 `opacity: 1`、`height: auto`、`visibility: visible` に切り替えることで表示させています。
フェードイン効果を実現するために `transition: opacity 0.5s` を使用しており、なめらかに内容が切り替わるのが特徴です。
また、高さや visibility も操作しているため、CSSだけではなく、HTMLの構造と連動してスムーズなUI切り替えが可能になります。

📄 HTML

<div class="tabs">
  <div class="tabs__buttons">
    <button class="tabs__button tab-button is-active">タブ1</button>
    <button class="tabs__button tab-button">タブ2</button>
    <button class="tabs__button tab-button">タブ3</button>
  </div>
  <div class="tabs__content tab-content">
    <div class="tab-content__item is-active">タブ1の内容です。</div>
    <div class="tab-content__item">タブ2の内容です。</div>
    <div class="tab-content__item">タブ3の内容です。</div>
  </div>
</div>

🎨 CSS

.tab-content__item {
	visibility: hidden;
	opacity: 0;
	transition: opacity 0.5s;
	height: 0;
	overflow: hidden;
	background-color: #f9fafb;
	border-radius: 0.5rem;
	padding: 0;
}

.tab-content__item.is-active {
	height: auto;
	visibility: visible;
	opacity: 1;
	padding: 30px;
}

.tab-button {
	font-size: 16px;
	font-weight: 600;
	padding: 12px 16px;
	background-color: #e5e7eb;
	border: 1px solid #d1d5db;
	cursor: pointer;
	transition: all 0.3s;
	flex: 1;
}

.tab-button:first-child {
	border-radius: 0.5rem 0 0 0.5rem;
}

.tab-button:last-child {
	border-radius: 0 0.5rem 0.5rem 0;
}

.tab-button.is-active {
	background-color: #3b82f6;
	color: white;
	border-color: #3b82f6;
}

.tabs__buttons {
	display: flex;
	margin-bottom: 1rem;
}

🧠 JavaScript

const tabs = document.querySelectorAll('.tab-button');
const contents = document.querySelectorAll('.tab-content__item');

tabs.forEach((tab, index) => {
	tab.addEventListener('click', () => {
		tabs.forEach(t => t.classList.remove('is-active'));
		contents.forEach(c => c.classList.remove('is-active'));

		tab.classList.add('is-active');
		contents[index].classList.add('is-active');
	});
});

戻る