自定义单选按钮不能居中伪元素

Custom radio button cannot center pseudo element

我正在尝试创建自定义单选按钮,但在尝试了几种居中方法后我无法将伪元素居中。对于某些屏幕尺寸,它工作正常但有时会变得奇怪。

.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 的宽度和高度,请在 label 和 [=] 中使用 Flexbox display:flex 22=] in :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>