Search code examples
csshtmlbackgroundpositioning

How can I vertically and horizontally center a DIV?


The behavior of my background image is, that the image is always perfectly centered when I resize the browser window. It gets on the top, left, right and bottom the same "distance" to the edge of my browser window.

The CSS:

background-image: url("ipad.jpg");
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: 563.5px 800px;

I have a div overlaying this image and I would like it to behave in the same way like the background image, so that it is always centered above the background image in the same place.

Is that even possible? And if yes. How? I hope you understand what I want to achive. :) Thank you very much for your help. :D


Solution

  • It looks like you're trying to center content horizontally as well as vertically, no matter what size the browser window is. If so, try something like this:

    Your HTML:

    <div class="outer">
        <div class="middle">
            <div class="inner">
                The content that you want centered.
            </div>
        </div>
    </div>
    

    Your CSS:

    /* Vertical and horizontal centering */
    .outer {
        position:fixed;
        top:0; left:0;
        width:100%; height:100%;
    }
    .middle { 
        height:100%; 
        display:table; 
        margin:0 auto;
    }
    .inner { 
        vertical-align:middle; 
        display:table-cell;
    }
    

    Good luck!

    Edit: Here's an example of the above - http://jsbin.com/aguciw