简体   繁体   中英

Vertically align dynamic text within a fixed div

I have a div that has a height of 200px. I have text in there that is sometimes one line, sometimes two lines. How would I center the text in there when the text's height changes? It seems like it would be simple to do but I cannot find a solution anywhere.

Right now my html is <div class="class1"><?php echo $variable; ?></div> <div class="class1"><?php echo $variable; ?></div>

and my css is

.class1 {
display:inline-block;
position:absolute;
left:235px; //Unimportant to question
height:200px;
width:415px;
top:15px;
text-align:center;
font-size:36px;
vertical-align:middle;
}

Although this doesn't center it. I have tryed using line-height:200px; , although then when my text becomes two lines the next line is 200 pixels under the first one.

You can add a dummy element (or use :before ) and set its height to 100%. Then, using inline blocks and vertical-align , you can vertically center:

.vertical-center:before, .vertical-center > * {
    display: inline-block;
    vertical-align: middle;
}
.vertical-center:before {
    height: 100%;
    content:'';
}

Demo

By using vertical-align:middle; and display:table-cell; you can vertically the multi-line text.

jsFiddle example

div {
    width:200px;
    height:200px;
    border:1px solid #999;
    display:table-cell;
    vertical-align:middle;
}

Try adding

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

to your div.

Demo

You can use valign HTML attribute or vertical-align CSS property:

.your-div
{
    text-align: center;
    height: 200px;

    vertical-align: middle;
}

You are right, it is simple. Use following:

<div style="vertical-align: middle; ">
   <p>some text</p>
</div>

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