如何在页面上垂直居中并且h1和h1?

时间:2013-03-01 11:34:43

标签: html css

我目前正在做:

HTML:

 <div id="narrate">
    <h1>Imagine everything.</h1>
    <span class="preloading">
        <i class="icon-spinner icon-spin icon-2x"></i>
    </span>
</div>  

的CSS

#narrate {
    margin:0 ;
    padding: 0;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    height: 300px;
    width: 500px;
    margin-top: -50px;
    margin-left: -200px;
    height: 20px;
}

h1 {
    font-size: 3em;
    font-family: 'Source Sans Pro', sans-serif !important;
    font-weight: 700;
}

.preloading {
    height: 20px;
    visibility: hidden;
    text-align: center;
}

我希望h1和微调器图标都在页面中心,微调器图标在h1下方。

上面的代码并没有真正居中,有一些像素输出位置。

我试过了:

#narrate {
    margin:0 ;
    padding: 0;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    height: 300px;
    width: 500px;
    margin-top: -150px;
    margin-left: -250px;
    height: 20px;
}

2 个答案:

答案 0 :(得分:2)

尝试display:table-cell

#narrate {
    margin:0 ;
    padding: 0;
    text-align: center;
      display:table-cell;
    vertical-align:middle; background:grey;
    height: 300px;
    width: 500px;
}

<强> DEMO


试试这个

html, body{
    height:100%;
    margin:0;
    padding:0
}
#narrate {
     background:grey;
    height: 100%;
    width: 100%;
   position:relative;
    vertical-align:middle; 
   display:table;
}

h1 {
    font-size: 3em;
    font-family: 'Source Sans Pro', sans-serif !important;
    font-weight: 700; display:table-cell; 
    vertical-align:middle; 
    text-align:center;
}
span{
    display:block;
    font-size:12px
}

<强> DEMO 2

答案 1 :(得分:0)

如果您正在寻找div居中的hor和vert的定位,请使用margin:auto

#narrate {
    width: 380px;
    height: 280px;
    margin: 70px auto;
    background: #ccc;
    text-align: center;
}

<强>样本 http://jsfiddle.net/X9LfB/6/

修改

垂直中心需要你约束你的身体说500px,然后设置margin-top使它垂直居中。