在垂直对齐的Div上使用固定定位

时间:2014-05-22 06:08:09

标签: html css css-position vertical-alignment

希望有一个简单的解决方案。基本上我要做的就是在浏览器的垂直中心放置一个div(#hello),使用固定定位,这样它就不会在滚动时移动。到目前为止,这是我的HTML:

<section id="home">
    <div id="home-container">
        <div id="hello"></div>
    </div>
</section>

CSS:

#home {
    display: table;
    overflow: hidden;
    margin: 0px auto;
}

*:first-child+html #home {
    position: relative;
}

* html #home {
    position: relative;
}

#home-container {
    display: table-cell;
    vertical-align: middle;
}

*:first-child+html #home-container {
    position: absolute;
    top: 50%;
}

* html #home-container {
    position: absolute;top:50%;
}

*:first-child+html #hello {
    position: relative;
    top: -50%;
}

* html #hello {
    position: relative;
    top: -50%;
}

#home {
    height: 100%;
}

现在div正在&#34; home&#34;中垂直居中。部分但在滚动上移动。我已经尝试将#home和#home-container改为固定定位,但它不起作用。

如果类似的线程已经存在,我已经搜索了很多并道歉。希望有人能指出我正确的方向。提前谢谢!

3 个答案:

答案 0 :(得分:0)

将div垂直对齐到具有固定位置的垂直中心的概念是添加位置:固定属性(指定偏移),然后将负边距放在div高度的一半上方。假设#hello的高度为100px,例如:

    #hello {
      position:fixed;
      top:50%;
      margin-top:-50px;
    }

位置:固定; div将相对于您的文档窗口。

答案 1 :(得分:0)

您可以添加此样式。此外,您必须在中间添加一些内容,以便您可以正确检查,或者为父div提供一些高度(以px为单位)。没有高度的空父div不会反映更改。

#hello{
    position: fixed;
    top: 50%;
}

你可以检查这个小提琴:

http://jsfiddle.net/76a4j/6/

答案 2 :(得分:0)

用这个替换你的css

*{margin:0; padding:0;}
html, body{height:100%;}
#home{display:table; margin:auto; height:100%; width:100%; position:fixed; top:0px; left:0px;}
#home-container{display:table-cell; vertical-align:middle; text-align:center;}
#hello{display:inline-block;}

我为你做了一个小提琴。查看http://jsfiddle.net/fQwFL/

希望它能解决你的问题。