首页 > 解决方案 > 仅使用 CSS 更改所选答案的背景颜色

问题描述

当玩家点击答案框(选择它)时,我想改变答案的颜色,如下图所示。 在此处输入图像描述

这是我的 html 代码,单选框是标签的子项。我尝试了一些命令,例如:

.choices > input[type="radio"]:checked {背景:黄色;}

但似乎这不是真的。当我将 unchecked="checked" 放入单选框行时,有人请告诉我区别?

非常感谢大家!

 <!-- ---question1--- -->
              <div class="quest">
                <h1>Question 1 of 10</h1>
                <h5>Question 1</h5>
                <div class="group">
                  
                  <label for="opt1" class="choices">
                    <input type="radio" id="1" name="q1" value="o1" >Option 1<br>
                  </label>
                  <label for="opt2" class="choices">
                    <input type="radio" id="2" name="q1" value="o2" >Option 2<br>
                  </label>
                  <label for="opt3" class="choices">
                    <input type="radio" id="3" name="q1" value="o3" >Option 3<br>
                  </label>
                  <label for="opt4" class="choices">
                    <input type="radio" id="4" name="q1" value="o4" >Option 4<br>
                  </label>

                </div>
              </div>
              <!-- ---question2--- -->
              <div class="quest">
                <h1>Question 2 of 10</h1>
                <h5>Question 2</h5>
                <div class="group">
                  
                  <label for="opt1" class="choices">
                    <input type="radio" id="5" name="q2" value="o1" unchecked="checked">Option 1<br>
                  </label>
                  <label for="opt2" class="choices">
                    <input type="radio" id="6" name="q2" value="o2" unchecked="checked">Option 2<br>
                  </label>
                  <label for="opt3" class="choices">
                    <input type="radio" id="7" name="q2" value="o3" unchecked="checked">Option 3<br>
                  </label>
                  <label for="opt4" class="choices">
                    <input type="radio" id="8" name="q2" value="o4" unchecked="checked">Option 4<br>
                  </label>

              </div>
              </div>

标签: htmlcss

解决方案


有些人已经指出,checked + label 是一种可能的解决方案。这是示例,但有所缩短。

input[type="radio"]:checked + label {
  background: yellow;
}
 <!-- ---question1--- -->
<div class="quest">
  <h1>Question 1 of 10</h1>
  <h5>Question 1</h5>
  <div class="group">
    <div>
      <input type="radio" id="1" name="q1" value="o1">
      <label for="1"> Option 1 </label>
    </div>
    <div>
      <input type="radio" id="2" name="q1" value="o2">
      <label for="2"> Option 2</label>
    </div>
  </div>
</div>


推荐阅读