简体   繁体   English

如何在行内div div中的div中垂直对齐文本?

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

Pls see the code: 请查看代码:

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

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

CSS 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. 我不知道为什么row1和row2中的文本与两个div的边框重叠。 I want to vertical-align them to the bottom. 我想将它们垂直对齐到底部。 Anybody know the reason? 有人知道原因吗?

Many thanx. 许多thanx。

Why not just halve your height / line-height in .container and remove the height:50%; 为什么不直接在.container height / line-height .container并移除height:50%; and line-height:50%; line-height:50%; from .row1 and .row2 . 来自.row1.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 而从除去50%的高度row1row2

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

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

JS Fiddle Demo JS小提琴演示

Similar to Dan's answer - http://jsfiddle.net/0kwnL8k8/4/ but I added another 'row' class for use in all rows. 与Dan的答案类似-http://jsfiddle.net/0kwnL8k8/4/,但我添加了另一个“行”类以用于所有行。 This does assume that the height is constant 30px. 这确实假定高度恒定为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? 我刚刚回答了一个类似的问题: 如何在具有百分比高度的div中间垂直对齐文本?

In your case it could be : http://jsfiddle.net/0kwnL8k8/5/ 在您的情况下,可能是: 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 请参阅此处链接的答案,以便在发生这种情况时管理多行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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