如何将复选框 - CSS下的自定义复选框标签居中?

时间:2017-07-22 16:43:14

标签: html css css3 checkbox

我正在修改现有项目,该项目具有一些用于复选框的自定义CSS样式。目前复选框标签位于复选框的右侧,我想将复选框移动到标签上方。如何使用以下代码实现此目的?

<input type="checkbox" id="box-<%= tmp %>">
<label for="box-<%= tmp %>"><%= question.choiceAnswer[tmp] %></label>

input[type="checkbox"] { display: none; }

input[type="checkbox"] + label {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 20px;
  text-align: center;
  font-weight: 500;
  font-size: 0.85em;
  color: #232A33;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

input[type="checkbox"] + label:last-child { margin-bottom: 0; }

input[type="checkbox"] + label:before {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  border: 1px solid #232A33;
  position: absolute;
  left: 0;
  top: 0;
  opacity: .6;
  -webkit-transition: all .12s, border-color .08s;
  transition: all .12s, border-color .08s;
}

input[type="checkbox"]:checked + label:before {
  width: 10px;
  top: -5px;
  left: 5px;
  border-radius: 0;
  opacity: 1;
  border-top-color: transparent;
  border-left-color: transparent;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}

根据我的理解,典型的复选框没有隐藏,并且通过CSS添加了新复选框,但我不确定如何将标签移动到复选框下面,因为它似乎是单件。我可以通过修改上面的代码来实现这一目标,还是我最好从头开始?

提前致谢!

1 个答案:

答案 0 :(得分:0)

删除标签的左边距和伪元素input[type="checkbox"] { display: none; } input[type="checkbox"] + label { position: relative; margin-bottom: 20px; text-align: center; font-weight: 500; font-size: 0.85em; color: #232A33; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; } input[type="checkbox"] + label:last-child { margin-bottom: 0; } input[type="checkbox"] + label:before { content: ''; display: block; width: 20px; height: 20px; border: 1px solid #232A33; opacity: .6; -webkit-transition: all .12s, border-color .08s; transition: all .12s, border-color .08s; } input[type="checkbox"]:checked + label:before { width: 10px; top: -5px; left: 5px; border-radius: 0; opacity: 1; border-top-color: transparent; border-left-color: transparent; -webkit-transform: rotate(45deg); transform: rotate(45deg); }

的绝对定位

&#13;
&#13;
<input type="checkbox" id="box">
<label for="box">Label</label>
&#13;
setInterval
&#13;
&#13;
&#13;