复选框格式化和功能

时间:2016-01-15 07:56:49

标签: html css checkbox

HTML:

<input type="checkbox" id="checkentire"> PLAY ENTIRE LESSON
<br>
<input type="checkbox" id="checkloop"> LOOP

CSS:

input[type=checkbox] {
    width:45px;     
    margin:5px 0;
    cursor:pointer;
    vertical-align:middle;
}
input[type=checkbox]:hover {
    background:lightgreen;
}

问题:
1. input[type=checkbox]:hover - 根本不起作用。
2. cursor:pointer - 仅适用于图形符号,不适用于文本 3. width:45px - 增加图形边距而不是图形本身 4. vertical-align:middle - 图形和文字未对齐 5.只需点击图形,而不是图形和文字,打开和关闭工作。

3 个答案:

答案 0 :(得分:1)

在很多时候,为了控制复选框的外观和大小,您需要使用“自定义复选框”,在浏览器(*)上获得一致的好处,也可以使用圆圈代替正方形,或蓝色而不是红色,你也可以为:hover本身label,可能性很多,就像这样:

JS Fiddle -updated 2

#test-checkbox{
  display:none;
}
#test-checkbox + label{
  color:black;
  cursor:pointer;
}
#test-checkbox:checked + label{
  color:#0A0;
  cursor:pointer;
}
#test-checkbox + label:hover{
  outline:1px dotted blue;
  outline-offset:4px;
}
#test-checkbox + label::before{
  content:'';
  width:12px;
  height:12px;
  display:inline-block;
  border:2px solid #AAA;
  border-radius:3px;
  margin-right:5px;
  cursor:pointer;
  position:relative;
  top:2px;
}
#test-checkbox:checked + label::after{
  width:5px;
  height:12px;
  content:'';
  display:inline-block;
  border-right:4px solid #0A0;
  border-bottom:4px solid #0A0;
  position:absolute;
  left:14px;
  top:6px;
  -ms-transform: rotate(45deg); /* IE 9 */
  -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
   transform: rotate(45deg);
}
<input id="test-checkbox" type="checkbox">
<label for="test-checkbox">Check Me</label>

----------------------------------------------- ---------------------------------

(*) IE8不支持伪元素::before::after,它们是正确的语法,它支持:before和{{1}其他浏览器也支持这些浏览器,有关详情,请查看::before::after

答案 1 :(得分:1)

您可以将复选框元素包装在包装元素中,并使用相对和绝对定位。这样可以轻松控制宽度和垂直对齐以及悬停状态,以及您可以单击标签文本以选中复选框。

这是一个例子。这实际上就是bootstrap的作用。

.checkbox-wrapper {
  position: relative;
  display: inline-block;
  width: auto;
  margin-top: 10px;
  margin-bottom: 10px;
  background:tomato;
  padding: 0 20px;
}

.checkbox-wrapper label {
  display: inline-block;
  max-width: 100%;
  min-height: 40px;
  line-height: 40px;
  vertical-align: middle;
  padding-left: 20px;
  cursor: pointer;
}

.checkbox-wrapper input[type=checkbox] {
  position: absolute;
  margin: 0 0 0 -20px;
  top: 50%;
  transform: translate(0,-50%);
}

.checkbox-wrapper:hover {
  background:lightgreen;
}
<div class="checkbox-wrapper">
  <label for="checkentire">
    <input type="checkbox" id="checkentire">
    PLAY ENTIRE LESSON
  </label>
</div>

答案 2 :(得分:1)

您可以尝试这样做以使checkbox:hover正常工作。

https://jsfiddle.net/k7hcgjk5/1/

实际上,您无法直接自定义复选框。相反,只需创建一个自定义复选框样式的span 即可为您完成此任务。

编辑:好吧,我忘了。显然,要处理checked状态,您还需要为其添加自定义。我相应地更新了小提琴。

相关问题