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

时间:2018-03-17 06:15:21

标签: html css css3 flexbox pseudo-element

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

enter image description here



.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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

实际上问题是你的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 labelmargin:auto { {1}}将其垂直和水平对齐...

: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;
}