如何在单选按钮上单击显示CSS边框

时间:2015-02-19 21:47:07

标签: html css css-selectors

我想在单击该单选按钮时,在单选按钮旁边的图像周围显示边框。目前,我的CSS选择器知识缺乏,我没有得到预期的结果。

我的期望是当我点击一个单选按钮时,相应的图像应该突出显示,但它不是......

有什么问题?

label>img ~ .input:checked  {
	border: 2px solid #f00;
}
<table>
<tr>
<td><label>

    <img src="http://bighappyface.com/Happy%20Face%2050x50.png"><br />
	<input type="radio" name="page" value="original" />Original </label>
</td>
<td><label>
    <img src="http://bighappyface.com/Happy%20Face%2050x50.png"><br />
	<input type="radio" name="page" value="standard" checked="checked">Standard
</label></td>
</tr>
</table>

修改

到目前为止,答案重新排列HTML元素,从设计的角度来看这是不可取的。我更喜欢将文本保留在图像的底部,而不是上方。如果有一个答案可以保持html元素的顺序,我会重新接受......

3 个答案:

答案 0 :(得分:1)

您需要使用input而不是.input,因为该点代表一个类而您尚未指定类。此外,需要在要更改的元素之前写入:checked伪类。兄弟选择器~应该在理论上工作,但我必须重新安排html元素。使用Chrome,Opera和Firefox进行测试。

&#13;
&#13;
input:checked ~ img  {
	border: 2px solid #f00;
}
&#13;
<table>
<tr>
<td>
    <label>
        <input type="radio" name="page" value="original" /> Original<br />
        <img src="http://bighappyface.com/Happy%20Face%2050x50.png">
    </label>
</td>
<td>
    <label>
        <input type="radio" name="page" value="standard" checked="checked"> Standard<br />
        <img src="http://bighappyface.com/Happy%20Face%2050x50.png">
    </label>
</td>
</tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是一个满足您需求的解决方案:

<强> Live Demo

input:checked ~ img  {
    border: 2px solid #f00;

}

label, img {
    position: relative;
    top: -80px;
}

label, input[type=radio] {

  top: 60px;  
}

HTML:

<table>
<tr>
<td>
    <label>
        <input type="radio" name="page" value="original" /> Original<br />
        <img src="http://bighappyface.com/Happy%20Face%2050x50.png">
    </label>
</td>
<td>
    <label>
        <input type="radio" name="page" value="standard" checked="checked"> Standard<br />
        <img src="http://bighappyface.com/Happy%20Face%2050x50.png">
    </label>
</td>
</tr>
</table>

答案 2 :(得分:0)

小提琴链接

http://jsfiddle.net/abasnet/0535aymy/

input[type="radio"]:checked + img {
    border: 2px solid #f00;
}



<table>
<tr>
    <td>
        <input type="radio" name="page" value="original" />Original
        <img src="http://idzyanamohddahlan.files.wordpress.com/2011/02/2472566_f520.jpg">
    </td>
    <td>
        <input type="radio" name="page" value="standard" checked="checked">Standard
        <img src="http://idzyanamohddahlan.files.wordpress.com/2011/02/2472566_f520.jpg">
    </td>
</tr>

相关问题