作成方法:カスタムチェックボックス

CSSを使ってカスタムチェックボックスとラジオボタンを作成する方法を学ぶ。

デフォルト:

One
Two

One
Two

カスタムチェックボックス:

カスタムラジオボタン:

自分で試してみる

カスタムチェックボックスの作成方法

第1段 - HTMLを追加:

<label class="container">One
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>
<label class="container">Two
  <input type="checkbox">
  <span class="checkmark"></span>
</label>
<label class="container">Three
  <input type="checkbox">
  <span class="checkmark"></span>
</label>
<label class="container">Four
  <input type="checkbox">
  <span class="checkmark"></span>
</label>

第2段 - CSSを追加:

/* カスタムタグ(コンテナ) */
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
/* ブラウザのデフォルトのチェックボックスを非表示に */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}
/* カスタムチェックボックスを作成 */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
}
/* マウスオーバー時の灰色背景色の追加 */
.container:hover input ~ .checkmark {
  background-color: #ccc;
}
/* チェックボックスを選択すると、青い背景を追加 */
.container input:checked ~ .checkmark {
  background-color: #2196F3;
}
/* チェックマーク/インジケーターを作成(未選択時に非表示) */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}
/* 選択時にチェックマークを表示 */
.container input:checked ~ .checkmark:after {
  display: block;
}
/* 設定チェックマーク/インジケーターのスタイル */
.container .checkmark:after {
  left: 9px;
  top: 5px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 3px 3px 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

自分で試してみる

カスタム単選択ボタンの作成方法

インスタンス

/* カスタムタグ(コンテナ) */
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
/* ブラウザのデフォルト単選択ボタンの隠し */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}
/* カスタム単選択ボタンの作成 */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
  border-radius: 50%;
}
/* マウスオーバー時の灰色背景色の追加 */
.container:hover input ~ .checkmark {
  background-color: #ccc;
}
/* 単選択ボタンの選択時の青色背景の追加 */
.container input:checked ~ .checkmark {
  background-color: #2196F3;
}
/* 指示器(点/円 - 未選択時の非表示)の作成 */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}
/* 选中時の指示器(点/円)の表示 */
.container input:checked ~ .checkmark:after {
  display: block;
}
/* 指示器样式(点/圆)の設定 */
.container .checkmark:after {
  top: 9px;
  left: 9px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: white;
}

自分で試してみる