垂直对齐div的内容

时间:2015-07-22 07:05:03

标签: html css alignment

我想垂直对齐div的内容。

所以基本上'你好测试'应垂直位于div的中心。

Demonstration



.parent {
    background:blue;
    float:left;
    width:100%
}

.parent div {
    float:left;
    width:50%;
}

h1 {
    font-size:50px;
    margin:0;
    padding:0;
}

<div class="parent">

<div>
    <h1>hello!</h1>
    <p>test</p>
</div>

<div>
    <img src="http://placehold.it/250x250" />
</div>

</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:4)

您可以使用表格布局:

&#13;
&#13;
.parent {
    background:blue;
    width:100%;
    display: table;
}

.parent div {
    display:table-cell;
    vertical-align:middle;
    width:50%;
}

h1 {
    font-size:50px;
    margin:0;
    padding:0;
}
&#13;
<div class="parent">

<div>
    <h1>hello!</h1>
    <p>test</p>
</div>

<div>
    <img src="http://placehold.it/250x250" />
</div>

</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

现代flexbox解决方案(IE10 +和所有现代浏览器supported):

.parent {
    display: flex;
    align-items: center;
}

DEMO

您可以通过this excelent article了解flexbox的更多信息:)

答案 2 :(得分:0)

使用此css

body{
    margin:0 auto;
}
.parent {
    background:blue;
    float:left;
    width:100%
}

.parent div 
{
    text-align:center;
    width:50%;
    margin:0 auto;
}

h1 {
    font-size:50px;
    margin:0;
    padding:0;
}