CSS おれおれ Advent Calendar 2012 – 21日目
セフセフ。
iOSの選択ボタン。HTMLでいうチェックボタン的なもの。”Switch Control”というらしいです。

HTML
こんな感じです。
1 2 3 4 5 6 7 8 9 10 | < p > < label class = "switch" > < input type = "checkbox" /> < span class = "label" > < span class = "on" >ON</ span >< span class = "separator" ></ span >< span class = "off" >OFF</ span > </ span > </ label > </ p > |
ちょいと余分な空白が出るのが嫌だったので、
1 2 3 | < span class = "on" >ON</ span > < span class = "separator" ></ span > < span class = "off" >OFF</ span > |
ではなく
1 2 3 | < span class = "on" >ON</ span >< span class = "separator" ></ span >< span class = "off" >OFF</ span > |
としました。
あとspan.separator
は素直に画像の方が良いかも。
ラジオボタンは非表示に
display:none
で隠しておきます。
非表示でも<label />
は反応してチェックを切り替えてくれます。
角丸とONとOFFの間の丸ポチ
label.switch
にborder-radius
とoverflow:hidden
を指定します。後で内側の要素だけ動かして表示を切り替える想定。
1 2 3 4 5 6 7 8 9 10 | .switch { border : solid 1px #ccc ; display : inline-block ; height : 40px ; width : 100px ; /* 角丸 */ border-radius : 20px ; overflow : hidden ; } |
丸ポチはborder-radius
をいっぱいにかけて、丸にします。適当に影も付けておきます。
ONとOFF
サイズを固定にしておきます。
あとはグラデーションなど適当に。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | .switch .on, .switch .off { display : inline-block ; height : 40px ; line-height : 40px ; text-align : center ; width : 80px ; } .switch .on { background-color : #00f ; background-image : linear-gradient ( top , hsl( 214 , 90% , 40% ), hsl( 214 , 90% , 70% ) ); box-shadow : 3px 2px 10px rgba ( 0 , 0 , 0 ,. 2 ) inset , -3px 2px 10px rgba ( 0 , 0 , 0 ,. 2 ) inset ; color : #fff ; text-shadow : -1px -1px rgba ( 0 , 0 , 0 ,. 3 ); } .switch .off { background-color : #eee ; box-shadow : 5px 5px 10px rgba ( 0 , 0 , 0 ,. 2 ) inset ; color : #777 ; text-shadow : 1px 1px #fff ; } |
チェックが付いたら表示切替
iOS風選択ボタンのときと同じく、直接隣接結合子+
を使います。<input type="checkbox" />
が:checked
になったら、その直後に出現する<span />
の表示を変更します。
1 2 3 4 5 6 | .switch .label { margin-left : -60px ; } .switch :checked + .label { margin-left : 0 ; } |
外側.switch
はONとOFFの片方(と丸ポチ)分の幅しかありません。そこにoverflow:hidden
を指定しているので、一度に見えるのは片方です。
そこで内側.label
の位置を調節する事で、見えるものを変更する事が出来ます。
チェック時にアニメーション
transition
です。
1 2 3 | .switch .label { transition : margin . 1 s; } |
margin
の値に変更があった場合、一瞬ではなく0.1s
かけて変更します。
わーいできたよー
細かいところは実際のコードを見てください。また諸々ベンダープレフィックスが必要だったりします。