5
4

More than 3 years have passed since last update.

CSSだけでアコーディオン×ハンバーガーメニューを作る(コピペ可)

Posted at

CSSだけでアコーディオン×ハンバーガーメニューを作る

スマホ画面はヘッダーが小さくなり
押しにくいボタンになることが多いです。

そこでハンバーガーメニュー×アコーディオンを
使用してユーザー操作をしやすくしてあげましょう

ちなみにハンバーガーメニューとは以下のようなものです。

Image from Gyazo

ハンバーガーのような見た目のアイコンを
押すと画面外からニュルッとメニューが出てきます。
JSなどを使用してリッチに作ることも可能ですが
ここではCSSのみで実装します。

アコーディオンは以下の動作です。
Image from Gyazo

ここでは+ボタンを押すことで親要素が広がって子要素が出てきます。

では実際のコードを見てみましょう

index.html
 <div class="humb-menu">
    <input id="gnav-input" type="checkbox">
    <label for="gnav-input" id="gnav-btn">
      <div i class="fas fa-bars"></div>
    </label>

    <div id="gnav-content">
      <!-- タイトルを記載ください -->
      <div class="humb-menu__title">title</div>

      <label for="label1">
        <!-- 親要素の名前 -->
        <p>label</p><p></p>
      </label>
      <input type="checkbox" id="label1" class="cssacc" />
      <div class="accshow">
        <!-- 子要素の名前 -->
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
      </div>

      <label for="label2">
        <p>label</p><p></p>
      </label>
      <input type="checkbox" id="label2" class="cssacc" />
      <div class="accshow">
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
      </div>

      <label for="label3">
        <p>label</p><p></p>
      </label>
      <input type="checkbox" id="label3" class="cssacc" />
      <div class="accshow">
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
      </div>
    </div>
  </div>

labelが親要素となりcontent部分が子要素となります。
必要に応じてpタグをaタグに変更してリンクなどにして使用ください。
ハンバーガーボタン部分はfontawsomeを使用しています。

index.css
#gnav-btn {
    color: gray;
    padding: 10px;
    font-size: 30px;
    position: fixed;
    top: 10px;
    right: 10px;
    z-index: 100;
    background-color: white;
    border: solid 1px #d1caca;
    border-radius: 3px;
  }
  #gnav-input:checked ~ #gnav-content {
    top: 0;
  }
  #gnav-content {
    position: fixed;
    top: -100%;
    left: 0;
    z-index: 10;
    transition: 0.3s;
    width: 100%;
  }
  .humb-menu__title {
    padding: 1.5rem;
  }
  .humb-menu label {
    display: flex;
    justify-content: space-between;
    padding: 1.5rem;
    cursor: pointer;
    border-top: 0.5px solid #c7c5c5;
  }
  .humb-menu input {
    display: none;
  }
  .humb-menu .accshow {
    height: 0;
    overflow: hidden;
  }
  .humb-menu .accshow p {
    padding: 1.5rem;
  }
  .humb-menu .cssacc:checked + .accshow {
    height: auto;
  }
} 

コードの記述量をへらすため必要最小限の記載にしています。
必要に応じて装飾を加えてください。

動作としてはhtmlで非表示のチェックボックスを設置し
チェックの有無で動作するシンプルな内容です。

コピペすると以下の動作になります。
Image from Gyazo

5
4
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
5
4