简体   繁体   中英

CSS : How do I vertically-center align text in a div ? (or any other elements which is not a table)

To vertically-center align text in a table-cell, I use vertical-align: middle in the td .

But the above doesn't work with divs, spans, header and other non-table elements. So how can I vertically-center align text in such elements ?

如果它是单行文本,则可以将行高设置为与元素相同的高度。

There are many possibilities, each with it's advantages and drawbacks.

Here's a good article by Douglas Heriot explaining 5 others methods, and comparing them.

Just use the following style :

<style type="text/css">
    div {
            vertical-align: middle;
            display: table-cell;
        }
</style>

That way, you are "displaying" the div as a table-cell and since vertical-align works with table-cells, you're text will be center-vertically aligned.

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