垂直对齐中间的文本

时间:2014-09-07 09:05:19

标签: html css

我无法使用位置绝对方法垂直对齐中间的某些文本。 JSFIDDLE

HTML

    <div class="heighted">
    <div class="middle-wrapper">
        <span class="middle">text to be vertically aligned in the middle</span>
    </div>
</div>
<hr/>
<div class="heighted">
    <div class="middle-wrapper">
        <img class="middle" src="http://www.google.com/homepage/images/google_favicon_64.png" />
    </div>
</div>

CSS

    .heighted {
    background: gray;
    height: 100px;
}
.middle-wrapper {
    height: 100%;
    position: relative;
}
.middle {
    bottom: 0;
    margin: auto;
    position: absolute;
    top: 0;
}

添加代码时出现Stack Overflow错误,它可能是Stack Overflow中的错误,所以请点击链接。

2 个答案:

答案 0 :(得分:1)

line-height: 100px;设为.heighted.middle-wrapper.middle - DEMO

<强> CSS:

.heighted {
    background: gray;
    height: 100px;
    line-height: 100px;
}
.middle-wrapper {
    height: 100%;
    position: relative;
}
.middle {
    bottom: 0;
    margin: auto;
    position: absolute;
    top: 0;
}

<强> HTML:

<div class="heighted">
    <div class="middle-wrapper">
        <span class="middle">text to be vertically aligned in the middle</span>
    </div>
</div>
<hr/>
<div class="heighted">
    <div class="middle-wrapper">
        <img class="middle" src="http://www.google.com/homepage/images/google_favicon_64.png" />
    </div>
</div>

答案 1 :(得分:0)

您应该尝试display:table-cell;并使用vertical-align:middle;

检查多么惊人和优化: http://jsfiddle.net/9jugdtqx/2/

和: http://jsfiddle.net/9jugdtqx/3/