Center container horizontally and vertically

Posted by Joey on Stack Overflow See other posts from Stack Overflow or by Joey
Published on 2014-08-21T09:48:45Z Indexed on 2014/08/21 10:20 UTC
Read the original article Hit count: 191

Filed under:
|

Looking over other question on this site, I used a method of setting all the positions to 0 with auto margins, but this has some unwanted behavior.

If you resize the window vertically, the top of the container moves off of the top of the page. It needs to stop when it hits the top.

JSFIDDLE: http://jsfiddle.net/jd67ca5y/

HTML:

<div id="container">
    <p>This is the container.</p>
    <p>If you resize the JSFiddle window horizontally, you will see that the left edge of the box doesn't move past the left edge of the window. This is correct behaviour.</p>
    <p>Now if you move the window vertically, the top of this container will disappear off of the top of the window. This is wrong.</p>
</div>

CSS:

#container {
    margin:auto;
    height:300px;
    width:300px;
    top:0;
    bottom:0;
    left:0;
    right:0;
    position:absolute;
    border:1px solid;
    padding:10px;
}

© Stack Overflow or respective owner

Related posts about html

Related posts about css