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

时间:2014-09-15 17:00:40

标签: html css

请参阅代码:

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;
}

我不知道为什么row1和row2中的文本与两个div的边框重叠。我想将它们垂直对齐到底部。有人知道原因吗?

很多人。

3 个答案:

答案 0 :(得分:2)

为什么不将height / line-height中的.container / height:50%;减半,并从line-height:50%;和{{1}移除.row1.row2 }。

所以你的容器类将是:

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

row1row2

中移除50%的高度
.row1{
    background:#450011;
    font-size:12px;
}

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

<强> JS Fiddle Demo

答案 1 :(得分:2)

与Dan的答案相似 - http://jsfiddle.net/0kwnL8k8/4/ 但是我添加了另一个&#39; row&#39;用于所有行的类。这确实假设高度恒定为30px。

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

答案 2 :(得分:1)

我刚刚回答了类似的问题:How to vertically align text in the middle of a div that has a percentage height?

在您的情况下,可能是:http://jsfiddle.net/0kwnL8k8/5/

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

请参阅此处链接的答案,以便在发生这种情况时管理多行