下面的代码可以很好地垂直对齐div中的文本,但当我尝试将其居中时,只有需要换行的文本才会居中。当文本很短时,比如5-6个单词,文本就不居中。我不知道是因为我,还是我做错了什么。
我正在使用display: table-cell;进行垂直对齐。div和p元素在CSS中以相同的方式定义。查看代码以了解问题所在。
<style>
.outer { outline: 1px solid #eee; }
.outer > p {
display: table-cell;
height: 200px;
vertical-align: middle;
text-align: center;
}
</style>
<div class="outer">
<p>
This longer text will be vertically aligned.
</p>
</div>
<div class="outer">
<p>
This longer text will be vertically aligned and centered. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
</div>http://codepen.io/anon/pen/vGowKL
发布于 2016-05-24 23:44:50
您只需要将包装outer类声明为display: table和width: 100%...您已经将孩子的p设置为display: table-cell。更新代码:http://codepen.io/anon/pen/VaoOJp
.outer {
outline: 1px solid #eee;
display: table;
width: 100%;
}
.outer > p {
display: table-cell;
height: 200px;
vertical-align: middle;
text-align: center;
}<div class="outer">
<p>
This longer text will be vertically aligned.
</p>
</div>
<div class="outer">
<p>
This longer text will be vertically aligned and centered. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
</div>
发布于 2016-05-24 23:30:37
.outer >p {
display: flex;
height: 100%;
justify-content: center;
align-items: center;
}您可以使用flexbox来简化操作。
https://stackoverflow.com/questions/37417673
复制相似问题