使用CSS和Bootstrap创建自定义复选框

13
我用Bootstrap框架编写了以下标记。
<div class="col-md-4">
  <div class="custom-container">
    <img class="center-block img-responsive img-circle invite-contact-trybe" src="{$img}" alt="Contact Image">
    <input class="invite-contact-checkbox" type="checkbox">
  </div>
</div>

我想要实现以下功能:

复选框设计

是否有使用CSS实现的方法?

显然我需要3种状态:

初始状态:

.custom-container input[type=checkbox]{}

某种悬停状态:

.custom-container input[type=checkbox]:hover{}

当它被选中时:

.custom-container  input[type=checkbox]:checked{}

有人能提供一个解决方案吗?


这里有很多关于CSS3复选框和单选框的插件、想法等等,可以去Google搜索一下。Bootstrap只是CSS和JS,没有内置此功能。Bootstrap的开发者们特别避免对原生元素进行样式设置。 - Christina
1个回答

44

背景图片复选框替换

让我们来创建它

Screenshot

这是一个非常简单的示例,使用:before伪元素以及:checked:hover状态。

通过这个干净的HTML

<input type="checkbox" id="inputOne" />
<label for="inputOne"></label>

请注意匹配的forid属性,这将标签附加到复选框。此外,元素的顺序非常重要;标签必须在输入后面,以便我们可以使用input:checked进行样式设置。

除了这个基本的CSS之外

  • 复选框使用display: none隐藏,所有交互都通过标签完成

  • :after伪元素被赋予Unicode勾号(\2714),但也可以使用背景图像打勾。

  • 由于边框半径造成的锯齿状边缘可以通过匹配颜色的box-shadow来软化。当背景图像不是纯色块时,边框的内侧边缘看起来很好。

  • transition: all 0.4s创建了平滑的边框淡入/淡出效果。

我在CSS注释中添加了更多指导。

完整示例

input[type=checkbox] {
  display: none;
}
/* 
- Style each label that is directly after the input
- position: relative; will ensure that any position: absolute children will position themselves in relation to it
*/

input[type=checkbox] + label {
  position: relative;
  background: url(http://i.stack.imgur.com/ocgp1.jpg) no-repeat;
  height: 50px;
  width: 50px;
  display: block;
  border-radius: 50%;
  transition: box-shadow 0.4s, border 0.4s;
  border: solid 5px #FFF;
  box-shadow: 0 0 1px #FFF;/* Soften the jagged edge */
  cursor: pointer;
}
/* Provide a border when hovered and when the checkbox before it is checked */

input[type=checkbox] + label:hover,
input[type=checkbox]:checked + label {
  border: solid 5px #F00;
  box-shadow: 0 0 1px #F00;
  /* Soften the jagged edge */
}
/* 
- Create a pseudo element :after when checked and provide a tick
- Center the content
*/

input[type=checkbox]:checked + label:after {
  content: '\2714';
  /*content is required, though it can be empty - content: '';*/
  height: 1em;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  color: #F00;
  line-height: 1;
  font-size: 18px;
  text-align: center;
}
<input type="checkbox" id="inputOne" />
<label for="inputOne"></label>


1
非常好的回答,喜欢使用新的stackoverflow代码片段!非常感谢,我会在实现后在这里发布我的最终解决方案的链接。谢谢:D 声望++ - cwiggo
我担心使用CSS来硬编码图像。你能不能在这个解决方案中不使用<img>元素?我正在动态创建这些复选框! :) - cwiggo
@Chris - 你可以使用变量在HTML中的标签上放置背景图片,像这样:<label style="background: {$img}">,并从CSS样式表中删除当前的背景图片。这样你提供URL的方法就不会改变 :) - misterManSam
@misterManSam:你能帮我处理多张图片吗?当我尝试这段代码时,单张图片可以正常工作,但是多张图片会使第一张图片被选中,请帮忙解决。 - Rebecca
1
@Rebecca - 如果您仍在寻找解决方案,您只需要重命名每个idfor属性,以便每个复选框输入与其标签匹配。这里有一个例子 - misterManSam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接