css - 自定义复选框/单选按钮焦点

标签 css checkbox radio-button usability

我使用以下方法创建了自定义复选框/单选按钮:

<label class="container">One
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>

<label class="container">Two
  <input type="checkbox">
  <span class="checkmark"></span>
</label>

<label class="container">Three
  <input type="checkbox">
  <span class="checkmark"></span>
</label>

<label class="container">Four
  <input type="checkbox">
  <span class="checkmark"></span>
</label> 
/* Customize the label (the container) */
.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide the browser's default checkbox */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

/* Create a custom checkbox */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
  background-color: #ccc;
}

/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark {
  background-color: #2196F3;
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after {
  display: block;
}

/* Style the checkmark/indicator */
.container .checkmark:after {
  left: 9px;
  top: 5px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 3px 3px 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
} 

参见:https://codepen.io/abluegem/pen/xxxxqez 并且:https://www.w3schools.com/howto/howto_css_custom_checkbox.asp

现在我面临“焦点”状态的问题。这些按钮没有焦点状态。我尝试添加自己的 CSS,但它不起作用。

正如您所看到的,主要元素/标签是“标签”,它没有焦点状态。并且有输入标签,但它被隐藏了。

我想知道我是否可以在这些按钮上设置焦点状态。

最佳答案

要在自定义复选框中设置焦点样式,您需要在实际复选框具有焦点时更改不同元素的样式。

添加此 CSS:

    input:focus + .checkmark
    {
      background-color: red;
    }

引用:focusing on an element changes another's CSS

关于css - 自定义复选框/单选按钮焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249463/

相关文章:

html - 如何让输入单选元素(包括其文本)成为固定宽度?

选项卡的 CSS 构建器

css - 如何在不使用 `overflow: hidden` 或边距的情况下获得一个 block 来填充 float 旁边的剩余水平空间?

java - CheckBox 中的 setChecked 和 setSelected 不起作用

android - 以编程方式选中的 RadioButton 不会取消选中

jquery - 如果使用 jquery 检查单选按钮,则启用输入字段

css - 在纯 CSS 中带有描边的 flex 边框?

html - CSS 我在哪里更改标签的文本颜色

javascript - knockout 计算写入未触发

python - 如何使用 OpenCV 检测与文档中的线条相交的复选框