如何使用CSS将文本垂直对齐?

时间:2014-08-11 03:59:36

标签: html css alignment

我有以下代码。我不能让它在分区的中心对齐。请问,我可以提一些建议吗?感谢。

<!DOCTYPE html>
<html>
    <head>
        <style>
            .center {
                margin: auto;
                width: 70%;
                height:100px;
                background-color: yellow;
                text-align:center;
            }
        </style>
    </head>
    <body>
        <div class="center">How to get this text aligned in the center?</div>
    </body>
</html>

4 个答案:

答案 0 :(得分:3)

您需要line-height和vertical-align:middle属性。

height:100px;
line-height: 100px;
vertical-align: middle;

详细说明@Leo所说的,这是多行的代码:

FIDDLE

.centered {
    height: 400px;
    display: table-cell;
    vertical-align: middle;
}

答案 1 :(得分:1)

使用vertical-align

DEMO here

.center {
    margin: auto;
    width: 70%;
    height:100px;
    background-color: yellow;
    text-align:center;


  vertical-align: middle;
    line-height: 100px;

}

如果有多行,你应该使用

display:table-cell

DEMO

答案 2 :(得分:1)

如果您需要将多行文字居中。然后使用display: table-cell;检查 DEMO

.center {
    margin: auto;
    width: 70%;
    height:100px;
    background-color: yellow;
    text-align:center;
  display: table-cell;
  vertical-align:middle;
}

<强>更新

如果您只支持最新的浏览器,也可以使用CSS3 Flex属性。检查 DEMO

.center {
margin: auto;
width: 70%;
height:100px;
background-color: yellow;
text-align:center;
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align Vertical */
}

答案 3 :(得分:1)

如果height已修复,请为line-height使用相同的值。

height:100px;
line-height: 100px;

vertical-align: middle;不是必需的。

但是,如果高度是动态的,请使用:

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