如何更改单选按钮的颜色

时间:2017-07-26 12:31:39

标签: html css

是否可以通过CSS更改单选按钮的背景颜色? 我在互联网上查看,但我只在JS中找到解决方案,我不一定理解它们。我尝试了这个,但它不起作用:

input[type="radio"]:checked {
  background-color: red;
}
<div class="sound-signal">
  Signal sonore :
  <input type="radio" name="soundsignal" id="soundsignal" checked="checked">
  <label for="soundsignal">Oui</label>
  <input type="radio" name="soundsignal">
  <label for="soundsignal">Non</label>
</div>

1 个答案:

答案 0 :(得分:4)

有两种方法可以使用CSS设置单选按钮(顺便说一下复选框):

  • 通过样式标签的伪选择器和隐藏单选按钮

    /* completely hiding radio button */
    input[type="radio"] {
      display: none;
    }
    
    /* simulate radiobutton appearance using pseudoselector */
    input[type="radio"] + label:before {
      content: "";
      /* create custom radiobutton appearance */
      display: inline-block;
      width: 15px;
      height: 15px;
      padding: 3px;
      margin-right: 5px;
      /* background-color only for content */
      background-clip: content-box;
      border: 1px solid #bbbbbb;
      background-color: #e7e6e7;
      border-radius: 50%;
    }
    
    /* appearance of checked radiobutton */
    input[type="radio"]:checked + label:before {
      background-color: red;
    }
    
    /* resetting default box-sizing */
    *,
    *:before,
    *:after {
      box-sizing: border-box;
    }
    
    /* optional styles for centering radiobuttons */
    .sound-signal label {
      display: inline-flex;
      align-items: center;
    }
    <div class="sound-signal">
      Signal sonore:
      <input type="radio" name="soundsignal" id="soundsignal1" checked="checked">
      <label for="soundsignal1">Oui</label>
      <input type="radio" name="soundsignal" id="soundsignal2">
      <label for="soundsignal2">Non</label>
    </div>

  • 通过使用CSS appearance: none隐藏标准外观并应用自定义外观。不幸的是,这种方式在IE for Desktop中不起作用(但适用于Windows Phone的IE)。

    input[type="radio"] {
      /* remove standard background appearance */
      -webkit-appearance: none;
      -moz-appearance: none;
      appearance: none;
      /* create custom radiobutton appearance */
      display: inline-block;
      width: 15px;
      height: 15px;
      padding: 3px;
      /* background-color only for content */
      background-clip: content-box;
      border: 1px solid #bbbbbb;
      background-color: #e7e6e7;
      border-radius: 50%;
    }
    
    /* appearance for checked radiobutton */
    input[type="radio"]:checked {
      background-color: red;
    }
    
    /* optional styles for centering radiobuttons */
    .sound-signal {
      display: flex;
      align-items: center;
    }
    <div class="sound-signal">
      Signal sonore :
      <input type="radio" name="soundsignal" id="soundsignal1" checked="checked">
      <label for="soundsignal1">Oui</label>
      <input type="radio" name="soundsignal" id="soundsignal2">
      <label for="soundsignal2">Non</label>
    </div>