CSS – 如何样式选定的单选button标签?

我想添加一个样式到一个单选button的选定标签:

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> 

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; } 

任何想法我做错了什么?

 .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; } 
 <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> 

如果你真的想把checkbox放在标签内,可以尝试添加一个额外的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> 

CSS

 .radio-toolbar input[type="radio"]:checked ~ * { background:pink !important; } 

这将设置所选单选button的所有兄弟的背景。

当元素不是同胞时,您正在使用邻接的兄弟select符( + )。 标签是input的父母 ,而不是兄弟姐妹。

CSS没有办法根据它的后代(或其后的任何东西)来select一个元素。

你需要看看JavaScript来解决这个问题。

或者,重新排列你的标记:

 <input id="foo"><label for="foo">…</label> 

你可以添加一个跨度到你的HTML和CSS。

这里是我的代码示例…

HTML(JSX):

 <input type="radio" name="AMPM" id="radiostyle1" value="AM" checked={this.state.AMPM==="AM"} onChange={this.handleChange}/> <label for="radiostyle1"><span></span> am </label> <input type="radio" name="AMPM" id="radiostyle2" value="PM" checked={this.state.AMPM==="PM"} onChange={this.handleChange}/> <label for="radiostyle2"><span></span> pm </label> 

CSS使标准单选button在屏幕上消失并叠加自定义button图像:

 input[type="radio"] { opacity:0; } input[type="radio"] + label { font-size:1em; text-transform: uppercase; color: white ; cursor: pointer; margin:auto 15px auto auto; } input[type="radio"] + label span { display:inline-block; width:30px; height:10px; margin:1px 0px 0 -30px; cursor:pointer; border-radius: 20%; } input[type="radio"] + label span { background-color: #FFFFFF } input[type="radio"]:checked + label span{ background-color: #660006; }