LoginSignup
1
1

More than 3 years have passed since last update.

iPhoneのON,OFFスイッチのようなトグルスイッチを作ってみた

Posted at

CSSを使ってトグルスイッチの作り方

早速だけどコード

See the Pen zYGoYex by yamazaki (@y_m_z_k) on CodePen.

構成

HTML

HTMLはシンプルにチェックボックスとラベルのみ。

<div class="switch">
  <input type="checkbox" id="toggle" class="toggle" />
  <label for="toggle"></label>
</div>

CSS

CSSがメインとなる。

 .switch {
        margin-top: 4px;
        margin-left: 2px;
        font-size:24px;
        padding: 2px;
    }
    .switch input[type=checkbox]{
        position: absolute;
        opacity: 0;
    }
    .switch label {
        width: 2em;
        height: 2em;
        position: relative;
        cursor: pointer;
        display: block;
    }
    .switch label:before {
        content: '';
        position: absolute;
        width: 2em;
        height: 1em;
        left: 0.1em;
        transition: background 0.1s ease;
        background: #f1f1f1;
        border-radius: 50px;
        box-shadow: inset 0px 1px 1px rgba(171,66,63,0.5);
    }
    .switch label:after {
        content:'';
        position: absolute;
        width: 1em;
        height: 1em;
        border-radius: 50px;
        left: 0;
        transition : all 0.2s ease;
        box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);
        background: #fcfff4;
        animation: swich-off .2s ease-out;
        z-index:2;
    }
    .switch input[type=checkbox]:checked+label:before {
        background:#8ce196;
        box-shadow: inset 0px 1px 1px rgba(84,152,140,0.5);
    }
    .switch input[type=checkbox]:checked+label:after {
        animation: switch-on .2s ease-out;
        left: 1.1em;
    }

ポイント

CSSで何やっているかわからないかもしれないが、
重要なのは元のチェックボックスは非表示にして:beforeと:afterの疑似要素で表現していること

疑似要素とはCSSでHTMLの要素のようなものを表現できる。
contentプロパティによって文などを追加できる。

最後に

CSSで分かりやすいデザインを作るのは楽しいのでとりあえず最初になじみのあるこの実装に取り組んでみました。
完成した時は感動しました。。。
他にも簡単に作れるものがあれば教えてください。

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