Center a DIV horizontally and vertically

Nrc picture Nrc · Jan 2, 2013 · Viewed 334.6k times · Source

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"

Answer

iamnotsam picture iamnotsam · May 16, 2014

For modern browsers

When you have that luxury. There's flexbox too, but that's not broadly supported at the time of this writing.

HTML:

<div class="content">This works with any content</div>

CSS:

.content {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

Tinker with it further on Codepen or on JSBin

For older browser support, look elsewhere in this thread.