CSS - 如何设置所选单选按钮标签的样式?

AnA*_*ice 127 html css css3

我想为单选按钮的选定标签添加样式:

HTML:

<div class="radio-toolbar">
 <label><input type="radio" value="all" checked>All</label>
 <label><input type="radio" value="false">Open</label>
 <label><input type="radio" value="true">Archived</label>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.radio-toolbar input[type="radio"] {display:none;}
.radio-toolbar label {
    background:Red;
    border:1px solid green;
    padding:2px 10px;
}
.radio-toolbar label + input[type="radio"]:checked { 
    background:pink !important;
}
Run Code Online (Sandbox Code Playgroud)

我有什么想法我做错了吗?

Šim*_*das 270

.radio-toolbar input[type="radio"] {
  display: none;
}

.radio-toolbar label {
  display: inline-block;
  background-color: #ddd;
  padding: 4px 11px;
  font-family: Arial;
  font-size: 16px;
  cursor: pointer;
}

.radio-toolbar input[type="radio"]:checked+label {
  background-color: #bbb;
}
Run Code Online (Sandbox Code Playgroud)
<div class="radio-toolbar">
  <input type="radio" id="radio1" name="radios" value="all" checked>
  <label for="radio1">All</label>

  <input type="radio" id="radio2" name="radios" value="false">
  <label for="radio2">Open</label>

  <input type="radio" id="radio3" name="radios" value="true">
  <label for="radio3">Archived</label>
</div>
Run Code Online (Sandbox Code Playgroud)

首先,您可能希望name在单选按钮上添加该属性.否则,它们不属于同一组,可以检查多个单选按钮.

此外,由于我将标签放置为(单选按钮的)兄弟,我必须使用idfor属性将它们关联在一起.

  • 你刚刚杀死了键盘访问!希望您的所有用户都身体健康。...现在,如果您只是将单选按钮保留在那里,而不使用 `display:none;`,那么浏览器将使其与键盘一起工作得很好。 (6认同)
  • @Johncl那是真的.IE8没有实现`:checked`选择器. (2认同)

iai*_*ton 26

如果您确实要将复选框放在标签内,请尝试添加额外的span标签,例如.

HTML

<div class="radio-toolbar">
 <label><input type="radio" value="all" checked><span>All</span></label>
 <label><input type="radio" value="false"><span>Open</span></label>
 <label><input type="radio" value="true"><span>Archived</span></label>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.radio-toolbar input[type="radio"]:checked ~ * { 
    background:pink !important;
}
Run Code Online (Sandbox Code Playgroud)

这将为所选单选按钮的所有兄弟姐妹设置背景.

  • 我更喜欢这种方法,尽管我使用了不同的选择器(下面提到的“+”和 [在这个问题中](http://stackoverflow.com/q/14592768/957950)),因为我只想设置所选项目的样式。这个让我不用担心 `for` 属性。 (2认同)

Que*_*tin 6

+当元素不是兄弟元素时,您正在使用相邻的兄弟选择器().标签是输入的父级,而不是它的兄弟.

CSS没有办法根据它的后代(也没有跟随它的任何东西)选择一个元素.

你需要寻找JavaScript来解决这个问题.

或者,重新排列标记:

<input id="foo"><label for="foo">…</label>
Run Code Online (Sandbox Code Playgroud)