css单行或多行垂直对齐 [英] css single or multiple line vertical align
问题描述
我有一个标题,可以有一行或多行。
I have a title that can have one or more lines.
如何垂直对齐文本?如果它总是一行,我可以只设置行高到容器的高度。
How can I align the text vertically? If it was always one line I could just set the line-height to the container height.
我可以使用JavaScript,但我不是真的喜欢它,我正在寻找一个纯CSS的方式。
I can do it using JavaScript, but I don't really like it, I'm searching for a pure CSS way.
此外,如果容器可以用线条展开,这将是完美的,所以我可以在顶部和底部有相同的填充。
Also if the container could expand with the lines it would be perfect, so I can always have the same padding on the top and bottom.
推荐答案
为此,您可以使用 display:table-cell
属性:
For this you can use display:table-cell
property:
.inline {
display: inline-block;
margin: 1em;
}
.wrap {
display: table;
height: 100px;
width: 160px;
padding: 10px;
border: thin solid darkgray;
}
.wrap p {
display: table-cell;
vertical-align: middle;
}
<div class="inline">
<div class="wrap">
<p>Example of single line.</p>
</div>
</div>
<div class="inline">
<div class="wrap">
<p>To look best, text should really be centered inside.</p>
</div>
</div>
IE8&以上。阅读这篇文章了解详情: CSS技巧:垂直居中多层文本 。
But it works IE8 & above. Read this article for more info: CSS Tricks: Vertically Center Multi-Lined Text.
这篇关于css单行或多行垂直对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!