鶏口牛後な日々

心の赴くまま、やりたいことを仕事に。

checkboxのデザインを任意の画像で変更する考え方と実装方法

チェックボックスのデザインを別画像で置き換えたいことはありますよね。

チェックボックスのデザインを変える。考え方

今回は、Pugとstylusを使って書いたのですが、HTML/SCSSで書いている人用に、下に同様のものをそれぞれ追記しますので、必要な人はそちらを使ってください。

考え方としては、以下のような手順です。

HTML(Pug)側

  1. inputタグでチェックボックスを作る
  2. すぐ下にspanタグをつける。ここに、様々なデザインを施す。inputタグに直接デザインを施すことができないため。

SCSS(stylus)側

  1. checkboxそれ自体は、 display: none で見えなくする
  2. checkbox-iconクラスの、 ::after 擬似要素afterを加えたものに対して以下のスタイルを付与  - content: ""
     - display: inline-block
     - width / height
     - background-image, repeat, position, size
  3. あとは見た目を整えるため、paddingやvertical-alignを場合に応じて付与

実際のコード

[Pug]
  label
    input(type="checkbox" name="checkbox").checkbox
    span.checkbox-icon Remember me
  • : 必須のスタイル
[stylus]
.checkbox
*  display none
.checkbox-icon
  line-height 20px
.checkbox + .checkbox-icon:before  // チェック前
*  content ""
*  display inline-block
*  width 20px
*  height 20px
*  background-image url(/images/icons/icon-checkbox-off.png)
*  background-repeat no-repeat
*  background-size contain
*  background-position 2px 0px
  vertical-align middle
  padding-left 10px
.checkbox:checked + .checkbox-icon:before   // チェック後
*  content ""
*  display inline-block
*  width 20px
*  height 20px
*  background-image url(/images/icons/icon-checkbox-on.png)
*  background-repeat no-repeat
*  background-size contain
*  background-position 2px 0px
  vertical-align middle
  padding-left 10px

注:stylusでは擬似要素( ::after::checked )は、コロン1つ(eg. ".checkbox-icon:after")

HTML/CSS で書く場合

[HTML]
<label>
    <input type="checkbox" name="checkbox" class="checkbox">
    <span class="checkbox-icon">Remember me</span>
</label>
[SCSS]
.checkbox {
  display: none;
}
.checkbox-icon {
  line-height 20px
}
.checkbox + .checkbox-icon::before {
  content: "";
  display: inline-block;
  width: 20px;
  height: 20px;
  background-image: url(/images/icons/icon-checkbox-off.png);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: 2px 0px;
  vertical-align: middle;
  padding-left: 10px;
}
.checkbox::checked + .checkbox-icon::before {
  content: "";
  display: inline-block;
  width: 20px;
  height: 20px;
  background-image: url(/images/icons/icon-checkbox-on.png);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: 2px 0px;
  vertical-align: middle;
  padding-left: 10px;
}