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?

チェックボックスをinput要素のみでスライドスイッチにする

Last updated at Posted at 2024-10-03

チェックボックスをスライドスイッチにするとき、普通は label などを使い対象を指定するかと思います。

「でもやっぱり input のみでシンプルに実現したい!」

できます。

サンプルコード

まずはこちらをご覧ください。

<style>
    input[type="checkbox"] {
        --size: 24px;
        --scale: 0.8;

        appearance: none;
        cursor: pointer;
        margin: 0;
        height: var(--size);
        aspect-ratio: 2;
        border-radius: var(--size);
        background-color: #444444;

        &::before {
            content: "";
            display: block;
            height: var(--size);
            aspect-ratio: 1;
            border-radius: var(--size);
            background-color: #FFFFFF;
            transform: scale(var(--scale));
            transition: 0.2s;
        }

        &:checked {
            background-color: #24B441;

            &::before {
                transform: translateX(var(--size)) scale(var(--scale));
            }
        }
    }
</style>

<input type="checkbox">

See the Pen qiita-demo-checkbox-css by dojyorin (@dojyorin) on CodePen.

解説

デフォルトのチェックボックスを appearance: none; で無効化しているのと、普通は label を使用するところを ::before で代用しているのがミソです。

全チェックボックスをスライドスイッチにしたくなければ、適当にクラスを作ってセレクタに混ぜれば大丈夫です。

input[type="checkbox"].switch {/*...*/}

なお、原型は こちら の記事を参考にしました。感謝!

1
1
2

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?