CSS3でドロップダウンメニューを作ってみる

2024.09.20 09:00
2024.09.20 09:57
CSS3でドロップダウンメニューを作ってみる

グローバルメニューなどでよくつかう
ドロップダウンメニューをCSSのみで作ってみました。

デモはこちら

まずHTMLはこちら

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" media="all" href="style.css" />
  <title></title>  
</head>
<body>

  <ul class="gnav__lists">
    <li class="gnav__list">
      <a href="#">メニュー1</a>
        <ul class="gnav__dropdownLists">
          <li class="gnav__dropdownList"><a href="#">メニュー1-1</a></li>
          <li class="gnav__dropdownList"><a href="#">メニュー1-2</a></li>
          <li class="gnav__dropdownList"><a href="#">メニュー1-3</a></li>
        </ul>
    </li>
    <li class="gnav__list"><a href="#">メニュー2</a></li>
    <li class="gnav__list"><a href="#">メニュー3</a></li>
    <li class="gnav__list"><a href="#">メニュー4</a></li>
    <li class="gnav__list"><a href="#">メニュー5</a></li>
  </ul>

</body>
</html>

そしてCSS

ul,li {
  list-style: none;
  margin: 0;
  padding: 0;
}
.gnav__lists {
  display: flex;
  justify-content: space-between;
}
.gnav__list {
  height: 40px;
  background-color: #ddd;
  position: relative;
  width: 19.5%;
}
.gnav__list:hover {
  background-color: #ddd;
}
.gnav__list a {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  text-decoration: none;
  color: #333;
}
.gnav__list:hover a {
  background-color: #999;
  color: #fff;
}

.gnav__dropdownLists {
  display: none;
  width: 100%;
  position: absolute;
  top: 40px;
  left: 0;
}
.gnav__list:hover .gnav__dropdownLists {
  display: block;
}
.gnav__dropdownList {
  background-color: #ddd;
  height: 60px;
  position: relative;
}
.gnav__dropdownList a {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  text-decoration: none;
  position: relative;
}
.gnav__dropdownList a:hover {
  background-color: #eee;
  color: #333;
}

意外とシンプルで使い勝手が良いですね。

今回は以上です!