如何使这个按钮位置相对?

时间:2016-12-22 18:42:45

标签: html css css3 checkbox

我有一个复选框,我已将其转换为ON-OFF按钮。但它仅在标签具有position: absolute时才有效。如何使用position: relative实现相同目的,以免妨碍整个页面的显示?



input[type="checkbox"] {
    position:absolute;
    clip: rect(0,0,0,0);
    clip: rect(0 0 0 0);
}

input[type="checkbox"] + label {
    line-height: 30px; 
    height: 27px; 
    cursor: pointer;
    -webkit-transition: background-position 0.3s ease-in-out;
    -moz-transition: background-position 0.3s ease-in-out;
}

input[type="checkbox"] + label::before {
    content: ""; 
    width: 94px; 
    height: 27px;
    background: url(http://dl.dropbox.com/u/391082/sprite2.png) -56px 0;
    position: absolute;
    border-radius: 4px;
    -webkit-transition: background-position 0.3s ease-in-out;
    -moz-transition: background-position 0.3s ease-in-out;
}

input[type="checkbox"]:checked + label::before {
    background-position: -3px 0;
}

<input id=test type=checkbox value=test checked>
<label for=test></label>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

如果您提供label display: inline-block和高度/宽度,而您使用的是通用兄弟选择器~,那么您将有一个很好的解决方案

input[type="checkbox"] {
    position:absolute;
    clip: rect(0,0,0,0);
    clip: rect(0 0 0 0);
}
input[type="checkbox"] ~ label[for=test] {
  display: inline-block;
  line-height: 30px;
  height: 27px;
  width: 94px;
  cursor: pointer;
  -webkit-transition: background-position 0.3s ease-in-out;
  -moz-transition: background-position 0.3s ease-in-out;
}
input[type="checkbox"] ~ label[for=test]::before {
  content: "";
  width: 94px;
  height: 27px;
  background: url(http://dl.dropbox.com/u/391082/sprite2.png) -56px 0;
  position: absolute;
  border-radius: 4px;
  -webkit-transition: background-position 0.3s ease-in-out;
  -moz-transition: background-position 0.3s ease-in-out;
}
input[type="checkbox"]:checked ~ label[for=test]::before {
  background-position: -3px 0;
}
<input id=test type=checkbox value=test checked>

You<br> can 
<label for=test></label>
do like this

如果你完全控制标记,相邻的兄弟选择器+可能会更好

input[type="checkbox"] {
    position:absolute;
    clip: rect(0,0,0,0);
    clip: rect(0 0 0 0);
}
input[type="checkbox"] + label {
  display: inline-block;
  line-height: 30px;
  height: 27px;
  width: 94px;
  cursor: pointer;
  -webkit-transition: background-position 0.3s ease-in-out;
  -moz-transition: background-position 0.3s ease-in-out;
}
input[type="checkbox"] + label::before {
  content: "";
  width: 94px;
  height: 27px;
  background: url(http://dl.dropbox.com/u/391082/sprite2.png) -56px 0;
  position: absolute;
  border-radius: 4px;
  -webkit-transition: background-position 0.3s ease-in-out;
  -moz-transition: background-position 0.3s ease-in-out;
}
input[type="checkbox"]:checked + label::before {
  background-position: -3px 0;
}
You<br> can 
<input id=test type=checkbox value=test checked>
<label for=test></label>
do like this