简体   繁体   中英

How to vertically align text in div which in an inline-block div?

Pls see the code:

http://jsfiddle.net/hrhktkbzyy/0kwnL8k8/

<div>        
    <div class="container divinline">
    <div class="row1 ">ROW ONE</div>
    <div class="row2">ROW TWO</div>
</div>

CSS

.divinline{
    display:inline-block;
}

.container{
    line-height:60px;
    height:60px;
    background:#ffee12;
    width:50%;
    text-align:left;
}

.row1{
    background:#450011;
    font-size:12px;
    height:50%;
    line-height:50%;
}

.row2{
    background:#333333;
    font-size:12px;
    height:50%;
    line-height:50%;
    color:#FFF;
}

I don't know why the text in row1 and row2 overlapped the border of the two divs. I want to vertical-align them to the bottom. Anybody know the reason?

Many thanx.

Why not just halve your height / line-height in .container and remove the height:50%; and line-height:50%; from .row1 and .row2 .

So your container class would be:

.container{
    line-height:30px; //half previous value
    height:30px; //half previous value
    background:#ffee12;
    width:50%;
    text-align:left;
}

And remove 50% height from row1 and row2

.row1{
    background:#450011;
    font-size:12px;
}

.row2{
    background:#333333;
    font-size:12px;
    color:#FFF;
}

JS Fiddle Demo

Similar to Dan's answer - http://jsfiddle.net/0kwnL8k8/4/ but I added another 'row' class for use in all rows. This does assume that the height is constant 30px.

.row {
  line-height:30px;
  height:50%;
  font-size:12px;
}

I just answered a similar question : How to vertically align text in the middle of a div that has a percentage height?

In your case it could be : http://jsfiddle.net/0kwnL8k8/5/

.row1:before, .row2:after {
    content:'';
    height:100%;
    vertical-align:middle;
    display:inline-block;
}

See answer linked here on SO, to manage multilines if that happens

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