自定义复选框样式 - 选中/取消选中标签跳转

时间:2016-02-11 19:24:28

标签: html css

我正在使用CSS3设置复选框样式。一切正常,只要每当我选中并取消选中复选框时标签就会跳转。你能告诉我为什么吗?



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

input[type="checkbox"] + label::before{
  background-color: white;
  border: 1px solid #ccc;
  content: '';
  display: inline-block;
  height: 15px;
  width: 15px;
  text-align: center;
  margin: 0 5px -2px 0;
}

input[type="checkbox"]:checked + label::before{
  content: '\2713';
}

<div>
  <input type="checkbox" id="checkbox1">
  <label for="checkbox1">Check 1</label>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

您可以在伪元素中添加overflow hidden以防止跳跃效果。我还更新了css以补偿溢出以及箭头没有在框中正确居中的事实。

JSFIDDLE Example

以下是我的看法:

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

input[type="checkbox"] + label::before{
  background-color: white;
  border: 1px solid #ccc;
  content: '';
  display: inline-block;
  height: 22px; /*Change width and height to compensate*/
  width: 22px; 
  text-align: center;
  margin: 0 5px -2px 0;
  /*Added styles*/
  overflow: hidden;
  top: 3px;
  position: relative;
}

input[type="checkbox"]:checked + label::before{
  content: '\2713';
}

答案 1 :(得分:1)

您可以将伪元素的position设为绝对,并相应地放置它。

这是一个解决方案。

div
{
  padding-left:20px;
}
input[type="checkbox"]{
  display:none;
}

input[type="checkbox"] + label::before{
  background-color: white;
  border: 1px solid #ccc;
  content: '';
  display: inline-block;
  height: 15px;
  width: 15px;
  text-align: center;
  margin: 0 5px -2px 0;
  position:absolute;
  left:10px;
}

input[type="checkbox"]:checked + label::before{
  content: '\2713';
}
<div>
  <input type="checkbox" id="checkbox1">
  <label for="checkbox1">Check 1</label>
</div>

也可能有其他有吸引力的解决方案,这只是一个。

答案 2 :(得分:0)

<强>更新

正如OP报道的那样,演示中仍然存在(是?)跳跃行为。我添加了另外两个可能解决问题的属性。我得到了相同的预期结果,因此我无法自行测试(很难解决您能看到的问题)。

其他CSS

  margin: 0 5px -5px 0;
  line-height: 100%;
  position: relative; // This should keep the input positioned in one spot. 
  float: left; // This should keep any extra movements of label and/or input from jumping as well.

添加这两个属性的关键在于它们都将元素从文档的正常中取出,因此与通常轻推的其他元素几乎没有交互或取代输入和/或标签。

  • 寻找那种时髦的保证金抵消,为了抵消这种跳跃行为,我们总会加入这种保证金。

  • 平衡了neg和pos值

  • 并添加了line-height: 100%

    margin: 0 5px -5px 0; line-height: 100%;

同样将div替换为fieldset并不是必需的,只是看起来更好。 :)

&#13;
&#13;
input[type="checkbox"] {
  display: none;
}
input[type="checkbox"] + label::before {
  background-color: white;
  border: 1px solid #ccc;
  content: '';
  display: inline-block;
  height: 15px;
  width: 15px;
  text-align: center;
  margin: 0 5px -5px 0;
  line-height: 100%;
  position: relative;
  float: left;
}
input[type="checkbox"]:checked + label::before {
  content: '\2713';
}
&#13;
<fieldset>
  <input type="checkbox" id="checkbox1">
  <label for="checkbox1">Check 1</label>
</fieldset>
&#13;
&#13;
&#13;

相关问题