我想在一个div中居中未知长度的文本(确定它被限制到一定的大小,但我不知道是否需要一行或两行)。因此,我不能使用line-height
。我试图使用display: table-cell
,但比布局被破坏。我无法使用top
的一些技巧,因为我需要这个定位。垂直居中未知长度的文本里面的文本
样机:
原始代码:
HTML:
<div class="background"> </div>
<div class="TileText">MyText - Another long, long, long text</div>
CSS:
.background{
background-color:#000;
height: 400px;
width: 100%;
}
.TileText{
position: relative;
top: -135px;
max-width: 200px;
height: 80px;
background-color: #FFF;
color: #black;
clear: both;
padding-left: 10px;
}
当前状态:
HTML:
<img src="images/castle.png" width="300" height="333" title="Castle" alt="Castle" />
<div class="TileTextWrapper">
<div class="TileText">Text</div>
</div>
CSS:
.TileTextWrapper{
position: relative;
top: -135px;
max-width: 200px;
height: 80px;
background-color: #FFF;
color: #57abe9;
clear: both;
padding-left: 10px;
display: table;
}
.TileText{
display: table-cell;
vertical-align: middle;
}
更新:
现在文本是垂直对齐的。但恐怕display: table
只适用于现代浏览器。参考http://jsfiddle.net/hSCtq/11/:
浏览器兼容性:http://reference.sitepoint.com/css/display#compatibilitysection – 2012-01-18 18:36:42
以显示为中心的这个方法:表肯定会在IE8和后续工作。 – 2012-01-18 18:37:08
查看http://css-tricks.com/centering-in-the-unknown/。运行良好,如果您希望它能够在较旧的浏览器上运行,您只需将代码添加到代码中而不是使用':before'。 – Michael 2012-01-18 18:45:02