本文介绍了复选框样式只有CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复选框,我想对它进行设置。当复选框未被选中时,它应该有一个黑色的边框,当复选框被选中时,复选框应该是黑色的,没有挂钩。下面你看到我到目前为止做了什么。



我的代码:

  

在通讯为选中时更改样式改变背景颜色:

  .newsletter:checked + label:before {
background-color:black;
}

通过这种方式,点击我们的伪复选框或标签中的文本将勾选框(点击标签都会将焦点发送到该字段,所以用复选框将会检查它)。

I have a checkbox and i would like to style it. When the checkbox is unchecked it should have a black border and when the checkbox is checked the hole checkbox should be black without hook. Below you see what i have done so far. Sadly it wont work.

My Code:

<form>
    <input class="newsletter" type="checkbox" value="text">Ich möchte den Newsletter bekommen
</form>

input[type=checkbox]:not(old){
  width     : 13px;
  margin    : 0;
  padding   : 0;
  opacity   : 0;
}

.newsletter:unchecked{
    width:13px;
    height: 13px;
    border: 2px solid black;
border-radius:3px;
}

.newsletter:checked{
    width:13px;
    height: 13px;
    border: 2px solid black;
    background-color:black;
border-radius:3px;
}

The first part of my code should hide the current checkbox. The second part should be the checkbox when the box is unchecked and the third part when the box is checked. I thought this is how you are styling these checkboxes. What am i doing wrong?

解决方案

The first thing you need to do with your code is add a label, e.g.:

<form>
  <input class="newsletter" type="checkbox" value="text" id="newsletter" name="newsletter">
   <label for="newsletter">Ich möchte den Newsletter bekommen</label>
</form>

I've also added an id and name attribute to the checkbox. The id needs to be the same as the for attribute on the label for this trick to work.

Next, we need to visibly hide the checkbox. I tend to use a class of sr-only in the CSS to visibly hide things based on Yahoo's example:

.sr-only{
  height: 1px;
  width: 1px;
  overflow: hidden
  clip: rect(1px,1px,1px,1px);
  position: absolute;
}

Next we create a pseudo element before the label. For the style rules I'm using the adjacent sibling selector (+) to apply the rules when the label is an adjacent sibling of the checkbox. I'm keeping your class name so it'll only target labels that're siblings of class newsletter:

.newsletter:not(checked) + label:before{
  content:" ";
  display: inline-block;
  width:13px;
  height: 13px;
  border: 2px solid black;
  border-radius:3px;
}

The :not(checked) means apply these rules when newsletter is not checked.

To change the styles when newsletter is checked we change the background colour like this:

.newsletter:checked + label:before{
 background-color:black;
}

This way clicking our pseudo checkbox or the text in the label will check the box (clicking the label at all sends focus to the field, so with a checkbox will check it).

这篇关于复选框样式只有CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 17:00
查看更多