Search code examples
htmlcsscentering

Vertically center text in a 100% height div?


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

The div only contains a single line of text.

The div cannot have a fixed height.

So my question is.

How do I vertically center the line of text?

I have tried using:

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

If it is important the div is absolutely positioned.


Current 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;
}

Solution

  • This answer is no longer the best answer ... see the flexbox answer below instead!


    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;

    for example:

    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>​