我正在尝试创建自定义单选按钮,但在尝试了几种居中方法后,我无法将伪元素居中。对于某些屏幕尺寸,它工作正常,但有时会变得很奇怪。
.custom-radio {
display: none;
}
.custom-radio+label {
position: relative;
display: inline-block;
width: 15px;
height: 15px;
border: 1px solid rgba(0, 0, 0, 0.3);
border-radius: 50%;
}
.custom-radio+label:after {
content: "";
position: absolute;
width: 11px;
height: 11px;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
background: black;
border-radius: 50%;
}
.custom-radio.flex+label {
display: flex;
align-items: center;
justify-content: center;
}
<div class="input-wrapper">
<input type="radio" id='custom-radio' class='custom-radio'>
<label for="custom-radio"></label>
</div>
<div class="input-wrapper">
<input type="radio" id='custom-radio' class='custom-radio flex'>
<label for="custom-radio"></label>
</div>
实际上问题是你的
label
宽度和高度...它的15px
很奇怪,这阻止了从父级计算top:50%
和left:50%
值...尝试这样做16px
,它会工作得很好..
.custom-radio {
display: none;
}
.custom-radio+label {
position: relative;
display: inline-block;
width: 16px;
height: 16px;
border: 1px solid rgba(0, 0, 0, 0.3);
border-radius: 50%;
}
.custom-radio+label:after {
content: "";
position: absolute;
width: 11px;
height: 11px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: black;
border-radius: 50%;
}
<div class="input-wrapper">
<input type="radio" id='custom-radio' class='custom-radio'>
<label for="custom-radio"></label>
</div>
<div class="input-wrapper">
<input type="radio" id='custom-radio' class='custom-radio'>
<label for="custom-radio"></label>
</div>
如果您不想更改
label
的宽度和高度,请使用 display:flex
中的 Flexbox
label
和 margin:auto
中的 :after
将其垂直和水平居中对齐...
.custom-radio {
display: none;
}
.custom-radio+label {
position: relative;
width: 15px;
height: 15px;
border: 1px solid rgba(0, 0, 0, 0.3);
border-radius: 50%;
display: flex;
}
.custom-radio+label:after {
content: "";
width: 11px;
height: 11px;
background: black;
border-radius: 50%;
margin: auto;
}
<div class="input-wrapper">
<input type="radio" id='custom-radio' class='custom-radio'>
<label for="custom-radio"></label>
</div>
<div class="input-wrapper">
<input type="radio" id='custom-radio' class='custom-radio'>
<label for="custom-radio"></label>
</div>
对于之后,考虑与之前相同的宽度和高度,并使用比例使内圆根据需要变小。只有在这种情况下才会对齐:
.custom-radio+label:after {
top: 0;
left: 0;
width: 15px;
height: 15px;
transform: scale(65%) !important;
...
}