将文本垂直居中在100%高度div中? [英] Vertically center text in a 100% height div?

查看:276
本文介绍了将文本垂直居中在100%高度div中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的div是父div的高度的100%。

I am working with a div that is 100% of the parent divs height.

div只包含一行文本。

The div only contains a single line of text.

div不能有固定高度。

The div cannot have a fixed height.

所以我的问题是。

如何垂直居中文本行?

我已尝试使用:

display: table-cell;  
line-height:200%;

如果重要的是div是绝对定位的。

If it is important the div is absolutely positioned.



当前CSS

.requests {
    position: absolute;
    right: 0;
    height: 100%;
    width: 50px;
    padding: 0 10px;
    background-color: #69A4B5;
    display: table-cell;
    vertical-align: middle;
    border-bottom-right-radius: 5px;
}


推荐答案

david的回答中所述),您需要添加负上边距。如果你知道(或强制)只有一行文本,你可以使用:

To get it perfectly centered (as mentioned in david's answer) you need to add a negative top margin. If you know (or force) there to only be a single line of text, you can use:

margin-top:-0.5em;

例如:

http://jsfiddle.net/45MHk/623/

//CSS:
html, body, div {
    height: 100%;
}

#parent
{
    position:relative;
    border: 1px solid black;
}

#child
{
    position: absolute;
    top: 50%;
    /* adjust top up half the height of a single line */
    margin-top: -0.5em;
    /* force content to always be a single line */
    overflow: hidden;
    white-space: nowrap;
    width: 100%;
    text-overflow: ellipsis;
}

//HTML:
<div id="parent">
    <div id="child">Text that is suppose to be centered</div>
</div>​

最初接受的答案不会垂直居中的文本(它的中心是基于文本的顶部)。所以,如果你的父母不是很高,它不会看起来中心,例如:

The originally accepted answer will not vertically center on the middle of the text (it centers based on the top of the text). So, if you parent is not very tall, it will not look centered at all, for example:

http://jsfiddle.net/45MHk/

//CSS:
#parent
{
    position:relative;
    height: 3em;
    border: 1px solid black;
}

#child
{
    position: absolute;
    top: 50%;
}​ 

//HTML:
<div id="parent">
    <div id="child">Text that is suppose to be centered</div>
</div>​

这篇关于将文本垂直居中在100%高度div中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆