以前はアコーディオンを作成する場合に jQuery や JavaScript を使用していましたが、CSS3 のおかげで、CSS と form の inputタグで実現出来るようになりました。
チェックボックスとCSS3でアコーディオンを作る
以下の「クリックすると開閉するアコーディオン」をクリックしていただくと動作します。
フォームのチェックボックスの状態により表示が変わる仕組みです。チェックボックス自体は非表示(display:none)にし、CSS3のtransitionプロパティでアニメーションっぽくしています。
チェックボックスを表示すると…
チェックボックスを表示(display:none しない)すると動作が分かりやすいかもしれません。
HTMLは至って単純です
<input>要素と <label>要素を関連付けるために、<input>タグのid属性と <label>タグのfor属性は同じである必要があります。
HTML
<form> <input id="ac-check" class="ac-check" type="checkbox"> <label class="ac-label" for="ac-check">クリックすると開閉するアコーディオン</label> <div class="ac-content"> <p>コンテンツ1</p> <p>コンテンツ2</p> <p>コンテンツ3</p> </div> </form>
CSSもそれほど複雑ではありません
ポイントは、チェックボックスがchecked属性の時のプロパティ変更と隣接要素の指定(演算子:+)です。あとは応用でいろいろなバリエーションが可能だと思います。
CSS
.ac-check {
display: none; /*チェックボックスを非表示*/
}
.ac-label {
color: #04287e;
display: block;
margin-bottom: 1px;
padding: 10px;
padding-left: 26px;
font-weight: bold;
border-top: solid 3px #6db3f2;
}
.ac-label:before {
content: '\f054';
font-family: fontAwesome;
padding-right: 8px;
color: #6db3f2;
}
.ac-content {
height: 0;
opacity: 0;
overflow: hidden;
border-bottom: solid 3px #6db3f2;
transition: all 1s linear;
}
.ac-content p {
height: 0;
opacity: 0;
overflow: hidden;
}
.ac-content p:nth-of-type(1) {
transition: all 0.5s;
}
.ac-content p:nth-of-type(2) {
transition: all 1s;
}
.ac-content p:nth-of-type(3) {
transition: all 1.5s;
}
/*ここから下がポイント*/
.ac-check:checked + .ac-label + .ac-content {
height: auto;
opacity: 1;
}
.ac-check:checked + .ac-label + .ac-content p {
height: auto;
opacity: 1;
}
.ac-check:checked + .ac-label:before {
content: '\f078';
color: #6db3f2;
}
以上、ご参考になれば幸いです。


コメント