Why does my div not center properly?

Kev picture Kev · Mar 25, 2010 · Viewed 7k times · Source

I'm using $.blockUI with jQuery to show a modal dialogue. The HTML looks like:

<div id="progressDialogue" class="mp_modalpopup">
    <div class="mp_container">
        <div class="mp_header">
            <span id="pd_header_text" class="mp_msg">Please wait..</span>
        </div>
        <div class="mp_body">
            <img src="ajax-loader.gif" style="text-align:center" alt="loading" />
        </div>
    </div>
</div>

The CSS looks like:

.mp_modalpopup
{
    font-family: arial,helvetica,clean,sans-serif;
    font-size: small;
    padding: 2px 3px;
    bottom: 50%;
    right: 50%;
    position: absolute;
    width: 400px;
    z-index:999;    
}

.mp_container
{
    width: 400px;
    border: solid 1px #808080;
    border-width: 1px 1px;
    left: 50%;
    position: relative;
    top: 50%;
}

/* removed mp_header, mp_body, mp_msg CSS for brevity */

This will happily render smack bang in the center of the page on top of other HTML.

However if I set display:none in the .mp_modalpopup CSS class and then use $.blockUI to make it visible, in IE 8 the dialogue centers itself vertically but aligns left with half of the dialogue off the page and in Google Chrome and Firefox the dialogue is not visible at all (but blockUI is working because the page greys out).

This is the blockUI javascript:

$.blockUI.defaults.css = {};

$.blockUI({ 
    message: $('#progressDialogue'), 
    overlayCSS: { backgroundColor: '#000', opacity: 0.1 },
    css: {backgroundColor: '#00f', color: '#100'} 
});

Why is this happening?

Answer

Nick Craver picture Nick Craver · Mar 25, 2010

This is happening because blockUI is also trying to center your <div>. If you remove all positioning from your CSS, it should work.

Remove this:

bottom: 50%;
right: 50%;
position: absolute;

And this

left: 50%;
position: relative;
top: 50%;

Alternatively, you could disable the blockUI centering like this:

$.blockUI({ 
    centerX: false, 
    centerY: false, 
    message: $('#progressDialogue'), 
    overlayCSS: { backgroundColor: '#000', opacity: 0.1 },
    css: {backgroundColor: '#00f', color: '#100'} 
});