<p>在100%高度div的垂直中心</p>

时间:2014-02-28 15:49:17

标签: css center

我的div高度是100%,但是当我这样做时,我不知道如何在中心垂直居中P-tag。

我该怎么做?

HTML:

<div>
<p>This text has to be vertically centered.</div>
</div>

CSS:

html, body {
    height: 100%;
    width: 100%;
}

div {
    height: 100%;
    width: 100%;
    background: url(http://www.windsim.com/images/sky/sky_107.bmp) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

p {
    font-family: "Times New Roman", Times, serif;
    color: black;
    text-align: center;
    font-size: 65px;
}

1 个答案:

答案 0 :(得分:1)

一种方法是使用下面概述的方法,请注意body&amp; html样式是可选的,用于在提供的小提琴中创建更好的插图。

关键是<p>需要包含在父元素中,并且两者都需要下面列出的样式。

Fiddle

HTML

<div>
    <p>text</p>
</div>

CSS

html, body{
    height:100%;
    width:100%;
    margin:0;
    padding:0;

}
div {
  display: table;
  width: 100%;
  height: 100%;
  text-align: center;
}

p {
  display: table-cell;
  vertical-align: middle;
}

我还建议您查看some of the alternative approaches shown here