CSSだけで作るスマホ向けラジオボタン

CSSだけで作るスマホ向けラジオボタン

スマホだとラジオボタンみたいな細かい要素は押しにくいのでサクッと作ったものを共有します。

表示サンプル

クリックで選択状態の方が黒く塗りつぶされます。

IE8以下は非対応。そもそもスマホ用なのでいらんでしょう。

HTML

<ul class="radios">
    <li>
        <input type="radio" name="radio1" value="on" id="radio1-1" checked="checked" />
        <label for="radio1-1">ON</label>
    </li>
    <li>
        <input type="radio" name="radio1" value="off" id="radio1-2" />
        <label for="radio1-2">OFF</label>
    </li>
</ul>

ミソとしては、 <label> の中に <input> を入れず、隣り合わせる形にすること。

CSS

.radios {
    display:inline-block;
    margin:0;
    padding:0;
    clear:both;
}
.radios li {
    display:inline-block;
    position:relative;
    float:left;
    list-style:none;
    border:solid 1px #ddd;
    border-right:none;
    overflow:hidden;
}
.radios li:first-child {
    border-radius:5px 0 0 5px;
}
.radios li:last-child {
    border-right:solid 1px #ddd;
    border-radius:0 5px 5px 0;
}
.radios label {
    display:block;
    min-width:3em;
    text-align:center;
    background:#eee;
    background:-webkit-gradient(linear, left top, left bottom, from(#FFF),to(#EEE));
    background:-moz-linear-gradient(top, #fff, #eee);
    border:solid 1px rgba(255,255,255,0.2);
    padding:5px;
    text-shadow:0 1px 0 rgba(255,255,255,0.5);
}
.radios li:first-child label {
    border-radius:3px 0 0 3px;
}
.radios li:last-child label {
    border-radius:0 3px 3px 0;
}
.radios input[type=radio] {
    position:absolute;
    opacity:0;
    width:100%;
    height:100%;
    margin:0;
    cursor:pointer;
}
.radios input[type=radio]:checked {
    cursor:auto;
}
.radios input[type=radio]:checked + label {
    color:#fff;
    text-shadow:0 -1px 0 rgba(0,0,0,0.2);
    border:solid 1px rgba(0,0,0,0.1);
    background:#666;
    background:-webkit-gradient(linear, left top, left bottom, from(#313131),to(#626262));
    background:-moz-linear-gradient(top, #333, #666);
}

色などスタイルは適当に変えてください。
一部ベンダープレフィックスも省いているので適当に加えてください。

解説

ポイントとしては下記です。

  • ラジオボタンは「opacity」で透明化し <label> 内で全体化
  • 一番下の定義で、ラジオボタンがチェック状態の時に隣接する <label> のスタイル変更

↓のように何個でも繋げられます。

筆者について

KaBuKi
ゲームとジョジョを愛するファミッ子世代。好きな言葉は「機能美」。
公私ともにWebサービスを作る系男子。