我将以下单选按钮设置为一个百分比宽度的容器:
当然,中间的圆必须居中。
我发现使用伪元素定位非常棘手。
根据浏览器的宽度,圆并不总是水平居中。这是在调整窗口大小时的单选按钮的gif:
可以在保持百分比宽度的容器的同时使该圆心居中吗?
这是我的代码:
HTML:
<div class="form-section gender">
<div class="label-col">
<label>Gender</label>
</div>
<div class="form-section">
<input type="radio" name="gender" id="male" value="male" />
<label for="male"><span>Male</span></label>
</div>
<div class="form-section">
<input type="radio" name="gender" id="female" value="female" />
<label for="female"><span>Female</span></label>
</div>
</div>
CSS(从SCSS编译):
@charset "UTF-8";
.gender {
width: 80%;
margin: 0 auto;
}
.gender .form-section {
margin-top: 20px;
display: inline-block;
width: 70px;
}
.gender input[type=radio] {
display: none;
width: 30px;
}
.gender .form-section label {
display: inline-block;
cursor: pointer;
position: relative;
padding-left: 25px;
margin-right: 15px;
color: gray;
}
@keyframes fade-in {
from {
opacity: 0.7;
}
to {
opacity: 1;
}
}
.gender .form-section label:before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
margin-right: 10px;
position: absolute;
left: 0;
bottom: 1px;
background-color: transparent;
border: 2px solid gray;
border-radius: 50%;
}
.gender input[type=radio]:checked + label:before {
font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
content: "•";
color: blue;
font-size: 21px;
text-align: center;
line-height: 17px;
border: 2px solid blue;
animation: fade-in 1s;
}
.gender input[type=radio]:checked + label {
color: blue;
}
Codepen链接:http://codepen.io/anon/pen/JXxvZW
最佳答案
我已经使用translate
将内部点定位在标签中心,并更改了标签样式以添加外部边框
.gender {
width: 80%;
margin: 0 auto;
}
.gender .form-section {
margin-top: 20px;
display: inline-block;
width: 70px;
}
.gender input[type=radio] {
display: none;
width: 30px;
}
.gender .form-section label {
display: inline-block;
cursor: pointer;
position: relative;
width: 16px;
color: gray;
border: 2px solid grey;
border-radius: 50%;
height: 16px;
}
.gender .form-section label span {
margin-left: 25px;
}
@keyframes fade-in {
from {
opacity: 0.7
}
to {
opacity: 1
}
}
.gender .form-section label:before {
content: "";
}
.gender input[type=radio]:checked + label:before {
width: 8px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 8px;
background: blue;
position: absolute;
border-radius: 50%;
animation: fade-in 1s;
}
.gender input[type=radio]:checked + label {
border-color: blue;
}
<div class="form-section gender">
<div class="label-col">
<label>Gender</label>
</div>
<div class="form-section">
<input type="radio" name="gender" id="male" value="male" />
<label for="male"><span>Male</span>
</label>
</div>
<div class="form-section">
<input type="radio" name="gender" id="female" value="female" />
<label for="female"><span>Female</span>
</label>
</div>
</div>
关于html - 具有一定百分比宽度的容器中的单选按钮伪元素定位问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37111224/