1
1

More than 1 year has passed since last update.

inputのradioボタンをカスタマイズしようとして、borderが効かない時・・・

Last updated at Posted at 2021-10-31

はじめに

radioボタンのカスタマイズ、超めんどくせぇ・・・

そう思いませんか?擬似要素を使ったり、何か色々とコネコネせんとダメっぽい・・

と言うのを、思い知った記念の記事となります!

環境

・Nuxt.js
・bootstrap

あれ?radioボタンの色が変わらんのやけど??

普通にinputタグのbackgroundborderを変えたらいいのかな〜?とか思ってると、全然ダメでした。。。

index.vue
<template>
  <div>
        <input
          type="radio"
          v-for="j in question.num"
          :key="j"
          :value="Number(j)"
        />
  </div>
</template>

<style scoped>
input {
  background: greenyellow;
  border: red;
  width: 20px;
  height: 20px;
}
</style>

スクリーンショット 2021-10-31 15.44.33.png
なんでやねん!!:weary:

結論、擬似要素を使わないと無理です!!

「みんなやたらと擬似要素使ってるな〜」とか思ってると、、そもそも擬似要素を使わないとinputをカスタマイズすることは無理っぽいようでした・・:sweat_smile:

index.vue
<template>
  <div>
        <input
          type="radio"
          v-for="j in question.num"
          :key="j"
          :value="Number(j)"
        />
  </div>
</template>

<style scoped>
input[type="radio"] {
  -webkit-appearance: none;  /* フォーム要素のスタイルを初期化 */
  width: 20px;
  height: 20px;
  border: 1px solid red;
  border-radius: 50%;
}
/* 内側のマル */
input[type="radio"]:before {
  content: "";
  display: block;
  width: 60%;
  height: 60%;
  margin: 20% auto;
  border-radius: 50%;
}
/* 選択された時の内側のマルの色 */
input[type="radio"]:checked:before {
  background: greenyellow;
}
</style>

スクリーンショット 2021-10-31 16.00.53.png

重要なポイント

いくつか重要なポイントをご紹介!

まずはinputを初期化しないといけません!!

-webkit-appearance: none;  /* フォーム要素のスタイルを初期化 */

👆これ超重要!
これがないとborderが効きませんでした:disappointed:
これを追加することによって、自由にinputをカスタマイズすることが可能になります。

checked attributeを追加させるような処理は、特に何も書いていません!!

checked attributeとは👇こーゆーの

<input type="radio" checked>

もしchecked attributeが無いと、こんな感じになってしまいます!

input[type="radio"] {
  -webkit-appearance: none;
  width: 20px;
  height: 20px;
  border: 1px solid red;
  border-radius: 50%;
}

input[type="radio"]:before {
  content: "";
  display: block;
  width: 60%;
  height: 60%;
  margin: 20% auto;
  border-radius: 50%;
  background: greenyellow;
}

スクリーンショット 2021-10-31 16.10.52.png

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1