css - 在 div 内垂直居中未知长度的文本

标签 css html positioning

我想在一个 div 中居中放置一段未知长度的文本(好吧,它有一定的大小限制,但我不知道它是否需要一行或两行)。因此我不能使用 line-height。我尝试使用 display: table-cell,但布局被破坏了。我不能对 top 使用一些技巧,因为我需要它来定位。

Here is an example .

模型:

Mockup

原代码:

HTML:

<div class="background">&nbsp;</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/

相关文章:

css - 布局拼图 : align to Left AND Right plus a Centered box All connected with a Line

CSS偏移属性和静态位置

javascript - 如何在点击功能上淡出文字?

html - CSS悬停动画隐藏文本

javascript - 理解 HTML 中的 Jquery

html - 增加 <li> margin-bottom 而不向下推 bottom div

CSS定位问题

css - 使用伪元素覆盖滚动的div

javascript - 我的选择过程不匹配?

html - 无法将导航栏中的 Logo 与按钮对齐