LoginSignup
16
14

More than 5 years have passed since last update.

CSSのみでトグル式メニューを作る。

Last updated at Posted at 2015-11-25

JavaScript(jQuery)は使わずにトグル式メニューを作りました。
動作は、http://jsfiddle.net/junya_5102/tL4j9zmo/2/ で確認できます。

html


<div id="side-menu">
  <input id="side-menu-toggle" type="checkbox">
  <label class="toggle-switch" for="side-menu-toggle">side-menu</label>
  <ul class="menu-list">
    <li class="list-item"><a href="#">アイテム1</a></li>
    <li class="list-item"><a href="#">アイテム2</a></li>
    <li class="list-item"><a href="#">アイテム3</a></li>
    <li class="list-item"><a href="#">アイテム4</a></li>
  </ul>
</div>

CSS


/* トグルスイッチのデザイン */
.toggle-switch{
  display: block;
  width: 12em;
  font-size: 1em;
  background: #55BEFC;
  box-shadow: 1px 0 3px 0 #000;
  text-align: center;
}

#side-menu-toggle{
  display: none;
}

/* 非チェック時の.menu-list */
#side-menu-toggle:not(:checked) ~ .menu-list{
  width: 0;
}

/* チェック時の.menu-list */
#side-menu-toggle:checked ~ .menu-list{
  width: 12em;
}

.menu-list{
  display: inline-block;
  padding: 0;
  margin: 0;
  background: #F0F0F0;
  box-shadow: 1px 1px 3px 0 #000;
  overflow: hidden;

  /* menu表示時のアニメーション */
  transition: 1s;
}

.menu-list > .list-item{
  list-style: none;
}

.menu-list > .list-item a{
  display: block;
  padding-top: 0.5em;
  padding-bottom: 0.5em;
  padding-left: 0.5em;
  /* 単一行で表示 */
  white-space: nowrap;
  /* リンク下線非表示 */
  text-decoration: none;
  outline: none;
}

/* css4  */
.menu-list > .list-item a:-webkit-any-link{
  color: #000;
}

.menu-list > .list-item a:-moz-any-link{
  color: #000;
}

/* any-link 未対応ブラウザ用 */
.menu-list > .list-item a:link,
.menu-list > .list-item a:visited{
  color: #000;
}

/* リンクホバー時 */
.menu-list > .list-item a:hover{
  background: #303030;
  color: #fff;
}

メニュー表示アニメーション

メニューを閉じる際のアニメーションは省略しています。

左から右へ

sample_lr.gif


/* 非チェック時の.menu-list */
#side-menu-toggle:not(:checked) ~ .menu-list{
  width: 0;
}

/* チェック時の.menu-list */
#side-menu-toggle:checked ~ .menu-list{
  width: 12em;
}

.menu-list{
  display: inline-block;
  padding: 0;
  margin: 0;
  background: #F0F0F0;
  box-shadow: 1px 1px 3px 0 #000;
  overflow: hidden;

  /* menu表示時のアニメーション */
  transition: 1s;
}

上から下へ

sample_tb.gif


/* 非チェック時の.menu-list */
#side-menu-toggle:not(:checked) ~ .menu-list{
  height: 0;
}

/* チェック時の.menu-list */
#side-menu-toggle:checked ~ .menu-list{
  /* コンテンツ数によって調整 */
  height: 12em;
}

.menu-list{
  display: inline-block;
  width: 12em;
  padding: 0;
  margin: 0;
  background: #F0F0F0;
  box-shadow: 1px 1px 3px 0 #000;
  overflow: hidden;

  /* menu表示時のアニメーション */
  transition: 1s;
}


対応ブラウザ

Chrome , Firefox , Safari

16
14
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
16
14