首页 > 解决方案 > CSS中的大单选按钮设计

问题描述

当您将鼠标悬停时,选择上应该有红色边框,当您单击单选按钮时,它应该用一个圆圈来检查它,就像图像一样。

到目前为止,在我的 HTML 和 CSS 上,我将样式放在了我试图针对我的表单检查的地方,但这一个不起作用,我的设计与我想要的不一致。我怎样才能达到与上图相同的效果?

.form-check {
  border: 1px solid #dedede;
  background: #fff;
  border-radius: padding: 14px 15px 14px 45px;
  border-radius: 5px;
}

input[type="radio"].form-check-input {
  border-radius: 50%;
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

<div class="col-lg-7">
  <div class="b-container">
    <h3 class="q-item">Do you love web development and mobile development?</h3>
    <div class="form-check ps-0">
      <label class="form-check-label q_radio">Yes 
        <input class="form-check-input" name="" type="radio" value="Yes"> 
      </label>
      <label class="form-check-label q_radio">No 
        <input class="form-check-input" name="" type="radio" value="No" checked> 
      </label>
    </div>
  </div>
</div>

标签: htmlcss

解决方案


单选按钮是被替换的元素,因此超出了 CSS 的范围。

此问题的常见解决方案是隐藏本机单选按钮并使用其他(可样式化的)元素重建它,定位在原始位置。

在下面的代码片段中,原始收音机通过 隐藏visibility: hidden,并使用::after伪元素创建一个位于其上方的红色圆圈。

input[type=radio] {
  visibility: hidden; /* hide the native radio button */
}

label > span {
  margin: 0 1rem; /* leave room for the big button */
}

input[type=radio]::after { /* use a pseudo-element to build a replacement */
  content: '';
  position: absolute;
  
  /* make it a circle */
  width: 2rem;
  height: 2rem;
  border-radius: 50%;

  /* white bg, grey border */
  background: white;
  box-shadow: 0 0 2px 1px grey;
  
  /* fun fact: child visibility can be overridden */
  visibility: visible;
  
  /* alignment */
  display: flex;
  justify-content: center;
  align-items: center;
  
  /* text treatment */
  font-family: sans-serif;
  font-weight: bold;
  
  /* animate the box shadow change just for fun */
  transition: box-shadow 0.25s;
}

input[type=radio]:hover::after {
  box-shadow: 0 0 4px 4px red;
}

input[type=radio]:checked::after {
  content: '✔'; /* display a checkmark if it's selected */
  
  box-shadow: none;
  
  /* red bg, white fg */
  background: red;
  color: white;
}
<label><input name="x" type="radio" /> <span>A radio button</span></label>
<label><input name="x" type="radio" /> <span>A radio button</span></label>
<label><input name="x" type="radio" /> <span>A radio button</span></label>
<label><input name="x" type="radio" /> <span>A radio button</span></label>


推荐阅读