没有保证金,小时没有居中:0自动

时间:2018-01-19 15:24:01

标签: css css3

我正在尝试使用hr定位在div中垂直居中absolute。但是,如果我执行top:50%,则不会显示在中心。为什么会这样?以下是代码。 jsfiddle

margin: 0 auto解决了这个问题,这对我来说更加令人费解,因为这会将auto设置为左/右边距而不是顶部/底部边距。

.wrapper {
  width: 200px;
  height: 100px;
  background: blue;
  position: relative;
}

hr {
  width: 200px;
  border: 1px solid white;
  position: absolute;
  top: 50%;
}

.hr-margin-auto {
  margin: 0 auto
}
<div class="wrapper">
  <hr class="hr">
  <hr class="hr hr-margin-auto">

</div>

2 个答案:

答案 0 :(得分:2)

hr元素具有默认边距。这适用于您hr的第一个,以及它低于您定义保证金的原因。如果为两者设置margin: 0(如下所示),它们将出现在同一位置(垂直居中)。

另外,正如@Pete指出的那样,你必须添加transform: translateY(-50%);以获得精确的垂直居中(在这种情况下只有一个px差异,这就是为什么我之前没有添加它,但是如果你想要准确,那就必要了)

&#13;
&#13;
.wrapper{
  width:200px;
  height:100px;
  background:blue;
 position: relative;
}


hr{
  width:200px;
  border:1px solid white;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  margin: 0;

} 

.hr-margin-auto{
  margin:0 auto;
}
&#13;
<div class="wrapper">
  <hr class="hr">
  <hr class="hr hr-margin-auto">

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

从语义上讲,<hr>元素用于主题中断。

来自MDN

  

HTML <hr>元素表示之间的主题中断   段级元素(例如,故事中场景的变化,   或者将主题转移到一节);从历史上看,这一直是   呈现为水平规则或线条。虽然它可能仍然存在   在可视浏览器中显示为水平规则,此元素现在是   以语义术语定义,而不是表达术语,所以如果你   希望绘制一条水平线,你应该使用适当的CSS

如果你只是需要一条白线来横向剖析盒子,另一种选择是background-repeating-gradient ......

见下文,视觉输出是相同的......

.wrapper {
  width: 200px;
  height: 100px;
  background: blue;
  position: relative;
  background: repeating-linear-gradient( blue, blue 50px, white 50px, white 52px);
  display: inline-block;
}

.wrapper2 {
  width: 200px;
  height: 100px;
  background: blue;
  position: relative;
  display: inline-block;
}

hr {
  width: 200px;
  border: 1px solid white;
  position: absolute;
  top: 50%;
}

.hr-margin-auto {
  margin: 0 auto;
}

span {
  color: white;
}
<div class="wrapper">
  <span>With gradient...</span>
</div>

<div class="wrapper2">
  <hr class="hr hr-margin-auto">
  <span>With hr...</span>
</div>

相关问题