views:

45

answers:

1

Hello,

how to center a div across all browsers and behind this div there should be a transparent background layer covering entire screen of browser like lightbox.

Thanks

+2  A: 

If you give the div a fixed width, it's easy to use negative margins:

div {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 600px;
    height: 400px;
    margin-top: -200px;
    margin-left: -300px;
    z-index: 20;
}

Without a fixed height, you cannot center the div vertically without JavaScript. With a dynamic height, you can vertically center the div using a snippet like this (in jQuery):

$(function() {
    var mydiv = $('div');
    mydiv.css({
        top: $(window).scrollTop() + $(window).height() / 2 - mydiv.height() / 2
    });
});

As for the transparent overlay, just give it an absolute position and a full width and height:

div#overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #000;
    opacity: 0.5;
    filter: alpha(opacity=50);
    z-index: 10;
}

If you can ditch IE6 support, you can simply use position: fixed instead of absolute, that way the divs will be centered even if the user scrolls the page, and even when JavaScript is turned off.

Tatu Ulmanen
thanks for your help, how do i make it so that width of the middle div is equal to that of its content? Thanks
Sarfraz