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

标签 html css 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 添加的,但我不确定如何将标签移动到复选框下方,因为它们似乎是一个整体。我可以通过修改上面的代码来实现这一点,还是我最好从头开始?

提前致谢!

最佳答案

移除标签的左填充和伪元素的绝对定位 :before

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);
}
<input type="checkbox" id="box">
<label for="box">Label</label>

关于html - 如何在复选框 - CSS 下居中自定义复选框标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45256934/

相关文章:

html - 将 Logo 与导航保持在同一行

javascript - 计算整个 DOM 中选中的所有复选框,即使它们未与 DataTable 一起显示?

html - Jade 不呈现复选框文本?

html - Font Awesome 不适用于 HTML5 UP 模板

javascript - 设置显示='block'后div不显示;

javascript - 使 p 与放置在另一个 div 中的图像具有相同的宽度/高度

javascript - JQuery '$' 在我的 .JS 文件中得到 "ReferenceError: $ is not defined"

html - 选择内联到底部

angular - 类型 'checked' Angular 4 上不存在属性 'HTMLElement'

javascript - JavaScript 中的安全 API