Search code examples
htmlcsscenter

Center a DIV horizontally and vertically


Is there a way to CENTER A DIV vertically and horizontally but, and that is important, that the content will not be cut when the window is smaller than the content The div must have a background color and a width and hight.

I have always centered divs with the absolute positioning and negative margins like in the example provided. But it has the problem that it cuts the content on top. Is there a method to center the div .content without this problem?

I have the example here to play: http://jsbin.com/iquviq/1/edit

CSS:

body { margin: 0px; }

.background {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    background-color: yellow;
}

/* 
is there a better way than the absolute positioning and negative margin to center the div .content: div with background color a width and a hight?: 
*/ 


.content {
    width: 200px;
    height: 600px;
    background-color: blue;

    position:absolute;
    top:50%;
    left:50%;
    margin-left:-100px;/* half width*/
    margin-top:-300px;/* half height*/
}

HTML:

<div class="background">
    <div class="content"> some text </div>
</div>

My question is not duplicate of "How to center an element horizontally and vertically? " 1- My question was asked before. (just check dates). 2- My question ask very clearly and in black as condition: "the content will not be cut when the window is smaller than the content"


Solution

  • After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit

    .content {
            width: 200px;
            height: 600px;
            background-color: blue;
            position: absolute; /*Can also be `fixed`*/
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            /*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
            max-width: 100%;
            max-height: 100%;
            overflow: auto;
    }