我想在一個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