Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertical align a text?

How to vertically align the text in a floated div? For example: I have a dynamic content with fixed height. if the content is small or big it has to automatically vertically align.

Thanks

like image 523
Harry Avatar asked Jul 09 '09 04:07

Harry


People also ask

How do I vertically align text in CSS?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.

How do I center align text vertically in HTML?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

Does vertical-align work for text?

It only affects alignment for inline items like text. You want flex. And inline items are vertical aligned to line-height. So, add line-height: 200px to your div and you'll see.


2 Answers

Table cells are the easiest solution.

Javascript is an alternative (measure the size and text size of the div, then adjust padding, or lineheight, or whatever).

edit: Or this awesome css:

CSS

div#container {
    border: solid 1px;
    height: 300px;
}

div#content {
    border: solid 1px;
}

div#balance {
    border: solid 1px;
    /* gotta be 100% */
    height: 100%;
}

div.valign {
    /* firefox 2 */
    display: -moz-inline-box;
    /* everybody else */
    display: inline-block;

    vertical-align: middle;
}

/* IE 6 and 7 hack */
html* div.valign {
    display: inline;
}

HTML

<div id="container">
    <div id="balance" class="valign"></div>
    <div id="content" class="valign">
        Blah blah blah blah<br/>
        Blah blah blah blah<br/>
        Blah blah blah blah<br/>
        Blah blah blah blah<br/>
        Blah blah blah blah
    </div>
</div>

Been meaning to make a blog post about this for a while, I think it's time.

like image 96
Ryan Florence Avatar answered Sep 28 '22 07:09

Ryan Florence


<div style="display: table-cell; vertical-align: middle;">I'm in the middle!</div>
like image 45
JerSchneid Avatar answered Sep 28 '22 08:09

JerSchneid