inputタグのラジオやチェックボックスをボタン画像にする方法

こんにちは。カスミです。
さて以下のような悩みをお持ちですか?
inputタグのラジオやチェックボックスをデフォルトの仕様ではなく、画像ボタンにして機能させたい。
このような疑問に回答します。
実装サンプル
See the Pen IE labe 画像 by Kohei (@kouk05) on CodePen.dark
まずは実装サンプルをご確認ください。
ラジオボタン、チェックボックス共に画像を使っており、クリックすると機能しているのがわかります。
導入手順は以下になります。
htmlの記述例
<!-- ラジオボタン -->
<div class="radio">
<input id="radio-1" type="radio" name="radio" value="0000"/>
<label for="radio-1" class="radio-label">
<img src="http://placehold.jp/24/cccccc/ffffff/250x50.png?text=ラジオボタン01">
</label>
</div>
<div class="radio">
<input id="radio-2" type="radio" name="radio" value="0000"/>
<label for="radio-2" class="radio-label">
<img src="http://placehold.jp/24/cccccc/ffffff/250x50.png?text=ラジオボタン02">
</label>
</div>
<div class="radio">
<input id="radio-3" type="radio" name="radio" value="0000"/>
<label for="radio-3" class="radio-label">
<img src="http://placehold.jp/24/cccccc/ffffff/250x50.png?text=ラジオボタン03">
</label>
</div>
<!-- チェックボックス -->
<div class="check">
<input type="checkbox" checked id="check-1" name="" value=""/>
<label for="check-1" class="label">
<img src="http://placehold.jp/24/cccccc/ffffff/250x50.png?text=チェックボックス">
</label>
</div>
<div class="check">
<input type="checkbox" id="check-2" name="" value=""/>
<label for="check-2" class="label">
<img src="http://placehold.jp/24/cccccc/ffffff/250x50.png?text=チェックボックス">
</label>
</div>
<div class="check">
<input type="checkbox" id="check-3" name="" value=""/>
<label for="check-3" class="label">
<img src="http://placehold.jp/24/cccccc/ffffff/250x50.png?text=チェックボックス">
</label>
</div>
htmlの記述例です。
画像ボタンにするには、labelタグを使います。
inputタグのid名とlabelタグのforを同じ名前にしてください。
そうする事でinputのチェック機能を関連付けする事ができます。
関連付けしたら、labelタグ内にimgで画像ボタンを読み込ませましょう。
CSSの記述例
/* デフォルトのチェックボックスを非表示*/
input {
display: none;
}
/*チェック中のラベルにCSSを適用*/
input:checked + label img {
border: 2px solid red;
}
CSSでデフォルトで出てるチェックボックスを非表示。
チェック中のラベルを、わかりやすいようにCSSで装飾すれば完成です。
まとめ
ECサイトの検索フォームなどでは、わりと画像ボタンにすることが多いので、上記やり方がおすすめです。
以上で解説を終わります。
目次