1
1

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.

JSを使わないドロップダウンメニュー

Last updated at Posted at 2019-09-01

実行結果

左下にドロップダウンするメニューのサンプル

サンプルコード

<div class="dropdown-container" data-position="bottom-left" >
    <input type="checkbox" id="dorpdown-heading">
    <label for="dorpdown-heading">メニュー</label>
    <ul>
        <li>アイテム - 1</li>
        <li>アイテム - 2</li>
        <li>アイテム - 3</li>
        <li>アイテム - 4</li>
        <li>アイテム - 5</li>
    </ul>
</div>
.dropdown-container {
    position: relative;
}

.dropdown-container > input {
    display: none;
}

.dropdown-container > *:last-child{
    position: absolute;
    display: none;
    white-space: nowrap;
}

.dropdown-container[data-position="bottom-right"] > *:last-child{
    left: 0px;
}

.dropdown-container[data-position="bottom-left"] > *:last-child{
    right: 0px;
}

.dropdown-container > input:checked ~ *:last-child{
    display: block;
}

概説

チェックボックスはクリックするごとにチェックされている状態とチェックされていない状態を行き来するので、それを利用してドロップダウンメニューの表示を管理します。

  • .dropdown-container > input でチェックボックスそのものが表示されないように指定しています。
  • .dropdown-container はドロップダウンメニューを position: aboslute で指定する都合で、 position: relativeposition: absolute である必要があります。
  • .dropdown-container > *:last-child によってドロップダウンメニューが表示されているとき/されていないとき共通のスタイルを指定しています。
  • .dropdown-container > input:checked ~ *:last-child によって、チェックボックスが checked な場合にドロップダウンメニューが表示されるようにしています。
  • .dropdown-container[data-position="bottom-right"].dropdown-container[data-position="bottom-left"] > *:last-child によって、ドロップダウンメニューの表示位置を data-position で指定できるようにしています。
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?