我错过了垂直对齐此文本的内容?

时间:2017-09-06 16:25:02

标签: html css vertical-alignment centering

我可以将line-height设置为85px,它会垂直对齐,但我不会总是知道元素的高度。我确定我在这里遗漏了一些简单的东西......但我可以在.content类中修改哪些内容使文本垂直居中?

.tile {
  position: relative;
  width: 100px;
  height: 85px;
  display: inline-block;
  border: 1px solid red;
}
#container1 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

#container2 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.content {
  margin: auto;
  height: 100%;
  vertical-align: middle;
  text-align: center;
}
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile">
<div id="container1">
  <div id="container2">
    <div class="content">Test</div>
  </div>
</div>
</div>

2 个答案:

答案 0 :(得分:1)

您可以使用psuedo这样的元素:

.content:after {
  content: '';
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}

见下面的演示:

&#13;
&#13;
.tile {
  position: relative;
  width: 100px;
  height: 85px;
  display: inline-block;
  border: 1px solid red;
}
#container1 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

#container2 {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.content {
  margin: auto;
  height: 100%;
  vertical-align: middle;
  text-align: center;
}
.content:after {
  content: '';
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}
&#13;
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile"></div>
<div class="tile">
<div id="container1">
  <div id="container2">
    <div class="content">Test</div>
  </div>
</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

.content{
   padding: 30% 0;
}

它没有垂直居中,但一开始就应该足够了。

检查这个问题:

How do I vertically center text with CSS?