为什么我的 CSS 自定义单选按钮不起作用?

时间:2021-05-04 06:05:26

标签: html css

我尝试自己制作单选按钮,但单击标签或输入单选按钮后不起作用。 我的代码如下。

.radio input[type="radio"] {
    display: none;
}

.radio {
    margin-left: 5px;
    position: relative;
    padding-left: 22px;
}

.radio span {
    width: 18px;
    height: 18px;
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    position: absolute;
    display: inline-block;
    left: 0;
    top: 5px;
}

.radio span::after {
    content: "";
    width: 16px;
    height: 16px;
    background-color: #448899;
    border-radius: 50%;
    display: inline-block;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
}

.radio input[type="radio"]:checked ~ .radio span::after {
    transform: translate(-50%, -50%) scale(1);
}
<label class="radio">
    <span></span><input type="radio" name="time" value="2000" id="morning" required />
    上半天
</label>
<label class="radio">
    <span></span><input type="radio" name="time" value="2500" id="afternoon" />
    下半天
</label>

即使我将无线电检查连接到另一个元素,它仍然不起作用。

1 个答案:

答案 0 :(得分:0)

更新代码如下。

.radio {
      display: flex;
      align-items: center;
      margin-left: 5px;
      position: relative;
      padding-left: 22px;
      margin-bottom: 10px;
      cursor: pointer;
    }

    .radio input[type="radio"] {
      position: absolute;
      opacity: 0;
      z-index: -1;
    }

    .radio span {
      width: 18px;
      height: 18px;
      background-color: rgba(255, 255, 255, 1);
      border: 1px solid  #484848;
      border-radius: 50%;
      position: absolute;
      display: inline-block;
      left: 0;
    }

    .radio span::after {
      content: "";
      width: 16px;
      height: 16px;
      background-color: #448899;
      border-radius: 50%;
      display: inline-block;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) scale(0);
    }

    .radio input[type="radio"]:checked ~ span::after {
      transform: translate(-50%, -50%) scale(1);
    }
<label class="radio">
    <input type="radio" name="time" value="2000" id="morning" required />
    <span></span>
    上半天
  </label>
  <label class="radio">
    <input type="radio" name="time" value="2500" id="afternoon" />
    <span></span>
    下半天
  </label>

相关问题