您的位置:首页 > Web前端 > CSS

通过label标签重置input[radio]样式

2018-01-12 16:40 531 查看
一、基于默认的input[radio]标签很丑,很多时候都需要重写样式,下面就介绍下通过label标签重置input[radio]标签的方法;

二、准备首先我们需要给lable标签绑定input,然后再通过一个标签包含说明文字(这里选用span标签),代码如下

<div class="wrap">
<input type="radio" id="option1" name="mode" value = "0" class="option-radio" checked />
<label id="firstLabel" for="option1"><span class="">这是一行优雅的代码</span>  </label>
<input type="radio" id="option2" name="mode" value = "1" class="option-radio" />
<label for="option2"><span class="">这是一行特别优雅的代码</span></label>
</div>
三、接下来要在样式上做文章了,先把input的原样式隐藏,然后给label标签用背景图代替原有样式。这里需要注意的是display的设置,因为label本身是行内元素,如果需要选项在一行设置inline-block,需要换行则设置block。否则无法给label设置宽高,点击文字时候将没法触发label。样式如下

.option-radio{
display: none;
}
.option-radio+label{
margin-top: 20px;
display: block;
height: 20px;
width: 200px;
text-indent: 23px;
background: url("nocheacked.png") no-repeat left center;
cursor: pointer;
}
.option-radio:checked+label{
background: url("cheacked.png") no-repeat left center;

}
#firstLabel{
width: 170px;
}
.wrap{
margin:15px;
}
四、效果图



五、完整代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>改变单选样式</title>
</head>
<style>
.option-radio{ display: none; } .option-radio+label{ margin-top: 20px; display: block; height: 20px; width: 200px; text-indent: 23px; background: url("nocheacked.png") no-repeat left center; cursor: pointer; } .option-radio:checked+label{ background: url("cheacked.png") no-repeat left center; } #firstLabel{ width: 170px; } .wrap{ margin:15px; }

</style>
<body>
<div class="wrap">
<input type="radio" id="option1" name="mode" value = "0" class="option-radio" checked />
<label id="firstLabel" for="option1"><span class="">这是一行优雅的文字</span> </label>
<input type="radio" id="option2" name="mode" value = "1" class="option-radio" />
<label for="option2"><span class="">这是一行特别优雅的文字</span></label>
</div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css label input radio
相关文章推荐