SnippetUI

FAQアコーディオン

JavaScript不要でHTML5のdetails/summary要素とCSSのみで実装。スムーズな開閉アニメーションを持つ、アクセシビリティ対応済みのFAQ向けアコーディオンです。

HTMLCSS

ネイティブの detailssummary 要素を使用したセマンティックでアクセシブルなFAQアコーディオンです。JavaScriptを使わずHTML/CSSのみで構築されているため、SEOに強く非常に軽量です。さらにCSSでカスタムスタイリング、ホバーステート、スムーズなアイコンの回転アニメーションを追加しています。

FAQアコーディオンとは何ですか?

FAQアコーディオンは、ユーザーがコンテンツの表示・非表示を切り替えられるUIパターンです。よくある質問などで、ページのスペースを節約するためによく使用されます。

どのような仕組みですか?

ネイティブのHTML5 detailsおよびsummary要素を使用しています。summaryがクリックされると、ブラウザが自動的に関連するコンテンツを展開または折りたたみます。

<div class="faq-container">
  <details class="faq-item">
    <summary class="faq-summary">
      <span class="faq-question">FAQアコーディオンとは何ですか?</span>
      <svg class="faq-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <path d="m6 9 6 6 6-6"/>
      </svg>
    </summary>
    <div class="faq-content">
      <p>FAQアコーディオンは、ユーザーがコンテンツの表示・非表示を切り替えられるUIパターンです。よくある質問などで、ページのスペースを節約するためによく使用されます。</p>
    </div>
  </details>
  <details class="faq-item">
    <summary class="faq-summary">
      <span class="faq-question">どのような仕組みですか?</span>
      <svg class="faq-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <path d="m6 9 6 6 6-6"/>
      </svg>
    </summary>
    <div class="faq-content">
      <p>ネイティブのHTML5 detailsおよびsummary要素を使用しています。summaryがクリックされると、ブラウザが自動的に関連するコンテンツを展開または折りたたみます。</p>
    </div>
  </details>
</div>
.faq-container {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
  font-family: system-ui, -apple-system, sans-serif;
}

.faq-item {
  background-color: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.faq-item:hover {
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
  border-color: #d1d5db;
}

.faq-item[open] {
  border-color: #3b82f6;
}

.faq-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  cursor: pointer;
  list-style: none; /* デフォルトの三角形を非表示 */
  font-weight: 600;
  color: #1f2937;
}

/* Webkit向けにデフォルトの三角形を非表示 */
.faq-summary::-webkit-details-marker {
  display: none;
}

.faq-question {
  padding-right: 16px;
}

.faq-icon {
  flex-shrink: 0;
  color: #6b7280;
  transition: transform 0.3s ease;
}

/* detailsが開いているときにアイコンを回転 */
.faq-item[open] .faq-icon {
  transform: rotate(180deg);
  color: #3b82f6;
}

.faq-content {
  padding: 0 20px 20px;
  color: #4b5563;
  line-height: 1.6;
}

.faq-item[open] .faq-content {
  animation: fadeIn 0.4s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}