Sammy
Sammy

Reputation: 607

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?

Upvotes: 1

Views: 3243

Answers (3)

JMichelB
JMichelB

Reputation: 475

#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.

Upvotes: 0

Dan
Dan

Reputation: 3358

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

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174937

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/

Upvotes: 5

Related Questions