April 17, 2012

How to horizontally center a modal div even after the browser is resized?

Question by saganbyte

I m trying to add an item to the DOM using jquery. I want it to overlay on top(z-index) of all other content (there are hundreds of z-indices set already) and it should be center aligned at all times.

While adding this div to the DOM, i m setting its ‘left’ property to $(window).width()/2 – 971/2. 971 is the width of the div I m trying to add. This is the CSS for it

width: 971px;
height: 669px;
background-image: url(/path/to/image/);
position: absolute;
margin: 0px auto;
z-index: 2500; 

The problem is, the div does not stay centered after the browser is resized. I ve even tried with left: 50% and some negative left margin in pixels. If I set the ‘left’ property in relation with the ‘screen’ then it s centered only if the browser window is maximized by the user.

What is a good way to position this absolutely positioned div with a high z-index such that its always centered?

Answer by Mikey

#someId{
    width: 971px;
    height: 669px;
    padding: 0;
    border: 0;

    margin-left:-486px; /* 971/2 */
    margin-top:-335px; /* 669/2 */

    position: fixed;
    left: 50%;
    top: 50%;

    background-image: url(/path/to/image/);
    z-index: 2500;
}

I know you’ve said you tried this – but this has always worked for me in any browser running in standards compliant mode (even ie) it might have been thrown off by not taking border or padding into consideration. Here’s a working example: http://jsfiddle.net/U3RrT/

I’ve just realised that it may be because you have set an element above it with a different position property; try position:fixed;.

Answer by Starx

First, margin: 0px auto; is enough to horizontally centre a div. So, just removing the left property may be able to fix the issue.


IF not, since you are using jQuery, there is a .resize() event of windowwhich you can control to fix the appearance again.

For example

function resizeMyBox() {
  //code to resize
}       
$(function() {
   resizeMyBox();  // Resize on DOM ready
});
$(window).resize(function() {
   resizeMyBox(); //Resize again on every resize
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!