91
100

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CSSだけでアコーディオンを実装

Last updated at Posted at 2016-07-20

今回はCSSのみでアコーディオンメニューを実装します。

#DEMO
http://codepen.io/takanorioki4/pen/grZpOp

image.gif

#HTML
inputのcheckboxを使って開閉を判断します。

inputの属性をradioにすると、複数あるうちの1つのメニューしか開かないように設定できます。

radioにした時のDEMO

<div class="menu">
    <label for="menu_bar01">MENU01</label>
    <input type="checkbox" id="menu_bar01" class="accordion" />
    <ul id="links01">
        <li><a href="">Link01</a></li>
        <li><a href="">Link02</a></li>
        <li><a href="">Link03</a></li>
        <li><a href="">Link04</a></li>
    </ul>
    <label for="menu_bar02">MENU02</label>
    <input type="checkbox" id="menu_bar02" class="accordion" />
    <ul id="links02">
        <li><a href="">Link01</a></li>
        <li><a href="">Link02</a></li>
        <li><a href="">Link03</a></li>
        <li><a href="">Link04</a></li>
    </ul>
</div>

#CSS
inputのcheckedになっている時だけ要素が表示されるようにCSSで設定します。

overflow-y: hiddenがないとaタグの中身が見えてしまいます。お忘れなく。

.menu li {
    max-height: 0;
    overflow-y: hidden;
}

#menu_bar01:checked ~ #links01 li,
#menu_bar02:checked ~ #links02 li {
    max-height: 46px;
    opacity: 1;
}

以下全文

.menu {
	max-width: 400px;
	margin: 0 auto;
	padding: 0;
}

.menu a {
	display: block;
	padding: 10px;
	text-decoration: none;
	color: #000;
	line-height: 1;
}

label {
	display: block;
	margin: 0 0 2px 0;
	padding :12px;
	line-height: 1;
	color :#fff;
	background :#007bbb;
	cursor :pointer;
}

input {
	display: none;
}

.menu ul {
	margin: 0;
	padding: 0;
	background :#f4f4f4;
	list-style: none;
}

.menu li {
	max-height: 0;
	overflow-y: hidden;
	-webkit-transition: all 0.5s;
	-moz-transition: all 0.5s;
	-ms-transition: all 0.5s;
	-o-transition: all 0.5s;
	transition: all 0.5s;
}

#menu_bar01:checked ~ #links01 li,
#menu_bar02:checked ~ #links02 li {
	max-height: 46px;
	opacity: 1;
}
91
100
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
91
100

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?