我想在一个 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
只适用于现代浏览器。
最佳答案
我已经更新了你的 fiddle :
好像还可以
参见:http://jsfiddle.net/hSCtq/11/供引用。
我会将 .TileText
放在 .background
中。为了背景图像而创建一个空的 div 在语义上是不正确的,在大多数情况下也没有必要。单独背景 div 的一种情况是,如果您需要独立于内容设置背景图像的不透明度。
<div class="background">
<div class="TileText">MyText - Another long, long, long text</div>
</div>
.background {
background-color:#000;
height: 400px;
width: 100%;
display: table
}
.TileText{
max-width: 200px;
display: table-cell;
vertical-align: middle;
color: #fff;
clear: both;
padding-left: 10px;
}
相同答案的其他问题。
Horizontally and vertically center a pre tag without the use of tables?
The old center a image in a div issue ( image size variable - div size fixed )
此外,谷歌搜索“居中垂直文本 css”的第一个结果将为您提供我在 JSfiddle 中发布的相同代码结构
关于css - 在 div 内垂直居中未知长度的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8914624/