简体   繁体   中英

How do I vertically center text in a DIV using CSS?

I'm having trouble center text vertically in a DIV using CSS. I've followed the related answers here on SO and elsewhere, but can't seem to get it to work. My simplified scenario is

<div class="outer">
    <div class="header-title">
        <span class="header-text">This is the title</span>
   </div>
</div>

and

div.outer {
    position: relative;
    height: 200px;
    border-style: solid;
    border-width:1px;

}

div.header-title {
    position: absolute;
    font-size: 36px;
    height: 100%; /* required */
    color: green;
    border-style: dashed;
    border-width:1px;
}

span.header-text {
    vertical-align: middle;
    border-style: dotted;
    border-width:1px;
}

but the result (in Safari) leaves the 'header-text' span at the top of the 'header-title' div :

在此处输入图片说明

your example shows a good workaround for vertically centering elements in a div:

display: table-cell;
vertical-align: middle;

so add it to your div css:

div.header-title {
position: absolute;
font-size: 36px;
height: 100%; /* required */
color: green;
display: table-cell;
vertical-align: middle;
border-style: dashed;
border-width:1px;
}

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