Div未与顶部对齐

时间:2016-09-20 09:46:05

标签: html css vertical-alignment css-calc

为什么会这样?我需要一个可以解释为什么div没有正确对齐的人?

HTML和CSS:

.horizontal-ruler {
  width: 100%;
  height: 25px;
  line-height: 25px;
  display: block;
  font-size: 14px;
  color: #373737;
}
.horizontal-ruler .ruler-unit {
  width: 30px;
  text-align: center;
  display: inline-block;
  line-height: 25px;
  height: 25px;
  vertical-align: middle;
}
.h-ruler-first-line,
.h-ruler-second-line {
  width: calc(50% - 15px);
  margin: 12px 0;
  height: 1px;
  background-color: #373737;
  display: inline-block;
}
<div class="horizontal-ruler">
  <div class="h-ruler-first-line"></div><!--
--><div class="ruler-unit">24"</div><!--
--><div class="h-ruler-second-line"></div>
</div>

https://jsfiddle.net/6xuvr6vw/1/

正如您所见,.ruler-unit中未包含.horizontal-ruler

4 个答案:

答案 0 :(得分:1)

您还需要将<{1}}添加到行

vertical-align: middle
.horizontal-ruler {
  width: 100%;
  height: 25px;
  line-height: 25px;
  display: block;
  font-size: 14px;
  color: #373737;
}

.horizontal-ruler .ruler-unit {
  width: 30px;
  text-align: center;
  display: inline-block;
  line-height: 25px;
  height: 25px;
  vertical-align: middle;
}

.h-ruler-first-line,
.h-ruler-second-line {
  width: calc(50% - 15px);
  vertical-align: middle;
  margin: 12px 0;
  height: 1px;
  background-color: #373737;
  display: inline-block;
}

答案 1 :(得分:1)

您可以使用div:after伪元素,仅使用2个:before元素来实现此目标。

&#13;
&#13;
.horizontal-ruler{
  text-align: center;
  overflow: hidden;
  line-height: 25px;
  font-size: 14px;
  color: #373737;
  height: 25px;
}
.horizontal-ruler .ruler-unit {
  display: inline-block;
  vertical-align: top;
  position: relative;
  padding: 0 10px;
}
.horizontal-ruler .ruler-unit:before,
.horizontal-ruler .ruler-unit:after {
  background-color: #373737;
  position: absolute;
  margin-top: -1px;
  width: 9999px;
  height: 1px;
  right: 100%;
  content: '';
  top: 50%;
}
.horizontal-ruler .ruler-unit:after {
  right: auto;
  left: 100%;
}
&#13;
<div class="horizontal-ruler">
  <div class="ruler-unit">24"</div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

与您的解决方案稍有不同的方法 - 它在整个div上具有边框底部,并且文本的相对位置在线上,以使外观显示它是由文本内容分隔的两行。可能会更好 - 只是为了向您展示一种不需要太多代码来实现相同效果的替代方案。

.horizontal-ruler{
  border-bottom:solid 1px #373737;
  text-align:center;
}
.ruler-unit{
  font-size:24px;
  width:30px;
  margin:0 auto;
  padding: 0 10px;
  position:relative;
  top:14px;
  background:white;
}
<div class="horizontal-ruler">
<div class="ruler-unit">24"</div>
</div>

答案 3 :(得分:0)

raw_input添加到以下行:

vertical-align: middle

小提琴:https://jsfiddle.net/udwffajo/