开发者

How to position a div in the absolute center of a page?

Here's how I'm doing it and it does work:

#myDiv { 开发者_如何学运维background: red; width: 100px; height: 100px; margin-top: -50px; margin-left: -50px; position: absolute; top: 50%; left: 50%; }

<div id="myDiv"></div>

But the problem is when I scroll down the page, the div no longer appears in the center because it is positioned 50% off the top relative to the original view port height, not the current one. So I guess I would have to listen for a document scroll event and update the position of the div dynamically. Any idea how to do that?

Basically the effect I'm after is for the div to always be in the center even when the user scrolls.

or maybe there's even a pure css solution?


Use position: fixed; instead of position: absolute; The positioning (top, left etc) will remain the same, but in relation to the window, and not the document.

http://jsfiddle.net/jasongennaro/25WAg/


You're going to want position: fixed;.

To achieve the div in the center of the screen, you're going to want left: 50%; margin-left: -50px;

Note that the negative margin-left is half of the container's width


#myDiv {
    background: red;
    width: 100px;
    height: 100px;
    margin: auto;
    position: fixed;
}

#container {
    width: 90%;
    height: 90%;
}

Then for your HTML :

<div id="container">
    <div id="myDiv">DATA</div>
</div>

Tell me if it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜