自定义CSS复选框和多行对齐刻度

时间:2019-01-29 18:42:20

标签: css checkbox

我已经在:before上使用:after<span>伪元素创建了一个自定义复选框,该复选框在单行上效果很好,但是当还有更多复选框时,刻度线会悬停在复选框上方<span>中一行文本。

我尝试使用相对值进行定位,但没有任何效果。

<ul class="calendar-filter-menu-cont">
  <li>
    <label>
      <input type="checkbox">
      <span>One line</span>
    </label>
  </li>

  <li>
    <label>
      <input type="checkbox">
      <span>This is the second item in the list</span>
    </label>
  </li>

  <li>
    <label>
      <input type="checkbox">
      <span>This is the third item in the list</span>
    </label>
  </li>
</ul>


ul.calendar-filter-menu-cont {
  color: black;
  column-count: 3;
  max-width: 500px;
}
ul.calendar-filter-menu-cont > li {
  break-inside: avoid-column;
}
ul.calendar-filter-menu-cont > li label {
  display: flex;
  position: relative;
}
ul.calendar-filter-menu-cont > li label:not(:last-child) {
  margin-bottom: 10px;
}
ul.calendar-filter-menu-cont > li label input[type="checkbox"] {
  margin-right: 1em;
  opacity: 0;
}
ul.calendar-filter-menu-cont > li label input[type="checkbox"] + span:before {
  content: '';
  display: inline-block;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
  border: 1px solid #979797;
  width: .8em;
  height: .8em;
  background-color: #f3f3f3;
  box-shadow: inset 0 0 5px 0 rgba(0, 0, 0, 0.2);
}
ul.calendar-filter-menu-cont > li label input[type="checkbox"]:checked + span:after {
  content: '';
  position: absolute;
  top: .7ex;
  left: .35ex;
  width: .9ex;
  height: .45ex;
  background: rgba(0, 0, 0, 0);
  border: 3px solid blue;
  border-top: none;
  border-right: none;
  transform: rotate(-45deg);
}

演示:https://codepen.io/anon/pen/PVGxBz

1 个答案:

答案 0 :(得分:1)

所以问题在于您的:before:after的属性不一致。 :before垂直居中,:after顶部对齐。

如果您想将复选框居中放置在输入框中,例如:

enter image description here

您需要使选中标记居中,例如:

ul.calendar-filter-menu-cont > li label input[type="checkbox"]:checked + span:after {
  content: '';
  position: absolute;
  top: .7ex;
  left: .35ex;
  width: .9ex;
  height: .45ex;
  background: rgba(0, 0, 0, 0);
  border: 3px solid blue;
  border-top: none;
  border-right: none;
  top: calc(50% - 1px); // Addition
  transform: translateY(-50%) rotate(-45deg); // Change
}

更改包括添加top属性和向translateY添加transform

如果要使复选框的顶部与输入对齐,例如:

enter image description here

只需删除transform并将top属性更改为静态值,例如:

ul.calendar-filter-menu-cont > li label input[type="checkbox"] + span:before {
  content: '';
  display: inline-block;
  position: absolute;
  top: .3ex; // Change
  left: 0;
  /* transform: translateY(-50%); */ // Remove
  border: 1px solid #979797;
  width: .8em;
  height: .8em;
  background-color: #f3f3f3;
  box-shadow: inset 0 0 5px 0 rgba(0, 0, 0, 0.2);
}