CSS使一个元素的内容成为另一个元素

时间:2017-06-11 19:45:35

标签: css

我的html中有复选框和标签

HTML:

<input type="checkbox" id="priv_profile" class="styled_checkbox">
<label for="priv_profile">Private Profile</label>

CSS:

.styled_checkbox {
      position: absolute;
      opacity: 0;
    }
    .styled_checkbox +label {
      position: relative;
      cursor: pointer;
      padding: 0;
      color: white;
      top: 20px;
      font-family: Zona;
      letter-spacing: 1px;
      color: gray;
      font-size: 28px;
    }
    .styled_checkbox + label:before {
      content: '';
      margin-right: 10px;
      display: inline-block;
      vertical-align: text-top;
      width: 25px;
      height: 25px;
      background: #ddd;
    }
    .styled_checkbox:checked + label:before {
      background: #f35429;
    }
    .styled_checkbox:checked + label:after {
      content: '';
      display: inline-block;
      width: 8px;
      height: 17px;
      border: solid gray;
      border-width: 0 2px 2px 0;
      transform: rotate(45deg);
      position: relative;
    }

https://jsfiddle.net/kpc1L386/

无论何时选中我的复选框,标签后都会显示勾号,但我希望它出现在复选框内。如何实现?

1 个答案:

答案 0 :(得分:1)

使用absolute定位topleft来定位它。

.styled_checkbox {
  position: absolute;
  opacity: 0;
}

.styled_checkbox +label {
  position: relative;
  cursor: pointer;
  padding: 0;
  color: white;
  top: 20px;
  font-family: Zona;
  letter-spacing: 1px;
  color: gray;
  font-size: 28px;
}

.styled_checkbox + label:before {
  content: '';
  margin-right: 10px;
  display: inline-block;
  vertical-align: text-top;
  width: 25px;
  height: 25px;
  background: #ddd;
}

.styled_checkbox:checked + label:before {
  background: #f35429;
}

.styled_checkbox:checked + label:after {
  content: '';
  display: inline-block;
  width: 8px;
  height: 17px;
  border: solid gray;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
  position: absolute;
  top: 0;
  left: 8px;
}
<input type="checkbox" id="priv_profile" class="styled_checkbox">
<label for="priv_profile">Private Profile</label>