简体   繁体   中英

`vertical-align: middle` doesn't do what I expected

If I am in a table cell in a apply the CSS rule vertical-align: middle; to that cell then all the text centers vertically in the cell.

<table>
    <tr>
        <td style="vertical-align: middle;">
            I am vertically centered text!
        </td>
    </tr>
</table>

However, if I apply this to another element it functions differently or not at all. For example:

<div style="width: 300px; height: 400px; vertical-align: middle;">
    I am not vertically centered, but I wish I was :(
</div>

But then if I apply it to an image tag then it adjusts how the image is oriented with other inline elements.

Here is a jsfiddle with examples of all these scenarios.

My question is, how can I accomplish vertical center alignment within a simple DIV just like the way it behaves in a table cell?

Add display: table-cell to your div.

jsFiddle: http://jsfiddle.net/7FYBa/20/

<div class="outer" style="position:absolute;">
    <div class="inner" style="display:table-cell; vertical-align:middle;">
        I am not vertically centered, but I wish I was :(
    </div>
</div>

But of course. Vertical centering is pretty funky in CSS.

I'd suggest you read up on some of the vertical centering techniques out there. Different elements and considerations equate to different methods. Here's an article I'd suggest .

您可以使用jQuery http://jsfiddle.net/7FYBa/30/

vertical-align works for none-table-elements when you increase the line-height .

#elem {
    vertical-align: middle;
    line-height: 100px;
}

But of course layouting is not that easy using line-height .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM