在使用 FontAwesome 替换复选框并更改 div 颜色时将 div 中的复选框居中

Centering a checkbox within a div while using FontAwesome to replace the checkbox and changing the div color

我已经研究了好几个小时了,所以决定问问。我正在尝试用圆圈内的 Font Awesome 图标替换我的复选框 div。当复选框被选中时,圆圈的颜色应该会改变。

我已经设法让图标替换复选框,但我无法在选中时更改背景。我个人认为我想多了,它可能会做得更简单,但这就是我所拥有的。

HTML:

<div class="actions thread-actions">
   <div class="checkbox visible">
      <button class="action primary-action visible" title="$vbphrase[save_changes]">
         <label for="cb_visible"><input type="checkbox" name="visible" value="yes" id="cb_visible" checked /></label>
      </button>
   </div>
</div>

CSS: (SCSS)

$brand-success: #5cb85c !default;
$brand-danger: #d9534f !default;

.thread-actions .checkbox {
   input[type=checkbox] {
      position: absolute;
      margin-left: -100em;
      margin-right: 100em;
      font-size: 1em;
   }

   input[type=checkbox]:before {
      position: absolute;
      left: 99em;
   }
}

/* Colors ---------------------- */
.thread-actions input[type=checkbox]:checked {
   color: $brand-success;
}

.thread-actions {
   input[type=checkbox]:before {
      font-family: 'FontAwesome';
   }
}

.thread-actions {
   .checkbox.visible input[type=checkbox]:before {
      content: "\f023";
      margin: -22px 0px 0px 17px;
   }
   .checkbox.visible input[type=checkbox]:checked:before {
      content: "\f023";
      background-color: #ff0000;
      /*  f3c2  */
   }
}

.actions .action {
   font-size: 26px;
   border: 0;
   border-radius: 50%;
   height: 48px;
   width: 48px;
   position: relative;
}

如何实现这种效果?

我有一个直播PEN here,我一直在玩这个。

在从头开始并重新思考之后,我设法想出了一个解决方案。

不是用无意义的 divs 包围输入,然后尝试设置每个 div 的样式我只使用 输入.

要实现此效果,请先将标准复选标记推开:

input[type=checkbox] {
  font-family: 'FontAwesome';        // tell this element to use FA
  position: absolute;                // absolutely push this thing away
  margin-left: -100em;               // buh bye checkmark
  font-size: 26px;                   // FA icon size
}

取消复选框后,我们可以继续进行样式设置:

input[type=checkbox]:before {
  left: 100em;                   // where the checkmark should have been
  border-radius: 50%;            // circle
  position: absolute;            // we want it absolutely where we placed it
  text-align: center;            // FontAwesome icon alignment
  height: 40px;                  // height of the circle
  width: 40px;                   // width of the circle
  background-color: #337ab7;     // circle color
  color: white;                  // icon color
  content: "\f070";              // FA icon
}

以此为基础,我们可以通过简单地覆盖我们的基本样式来继续为我们的复选框设置样式:

input[type=checkbox]:checked:before {
  content: "\f06e";                // FA icon
  background-color:#be0000;        // circle color
}

有时回过头来重新思考事情会有所帮助,希望这对某人有所帮助 =)

Here is a live preview of the end result.