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

标签 html css twitter-bootstrap checkbox customization

我有以下使用 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>

我想实现以下目标:

Checkbox design

有没有办法使用 CSS 来做到这一点?

我显然需要 3 个状态:

初始:

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

某种形式的悬停状态:

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

选中时:

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

谁能提出解决方案?

最佳答案

背景图片复选框替换

让我们创建这个

Screenshot

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

有了这个干净的 HTML

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

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

设置样式

以及这个基本 CSS

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

  • :after 伪元素被赋予一个 unicode 标记 (\2714),但这也可以用背景图像标记。

  • 由 border-radius 引起的锯齿状边缘可以通过匹配颜色 box-shadow 来柔化。当背景图像不是纯色 block 时,边框的内边缘看起来很好。

  • 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>

关于html - 使用 CSS 和 Bootstrap 创建自定义复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26531642/

相关文章:

javascript - 当我重新加载页面时在脚本之前加载图像,可能会产生 FOUC 效果

css3 列顺序错误

html - 如何将 Bootstrap 下拉菜单设置为全页宽度?

html - Twitter Bootstrap 中的 8 列

javascript - 悬停时的 Bootstrap 子菜单

javascript - 检测文件是否应该从 UIWebview 下载

apache - HTML5 服务器发送事件原型(prototype)制作 - 模棱两可的错误和重复轮询?

javascript - 从下拉菜单中输出两个数组值的差异 (Javascript)

html - 固定位置内的绝对位置

php - CSS对齐来自循环帖子的网格元素