Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8700

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

$
0
0

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

早速だけどコード

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

構成

HTML

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

<divclass="switch"><inputtype="checkbox"id="toggle"class="toggle"/><labelfor="toggle"></label></div>

CSS

CSSがメインとなる。

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

ポイント

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

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

最後に

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


Viewing all articles
Browse latest Browse all 8700

Latest Images

Trending Articles