cointilt
cointilt

Reputation: 718

Javascript centering a div on the page

For javascript I use the jQuery framework but can easily integrate any javascript functions into it. The problem I have is I have a div that fade's in when I click a link. How can I get it to align in the center of the page and stay even when scrolling.

Below is an example of what I currently have implemented:

HTML code:

<div id="dividname">
    <h2>Heading Goes Here</h2>
    <p>content goes here</p>

    <p><a href="#" class="close-box">Close Box</a></p>
</div>

CSS code:

#dividname {
    position:absolute; z-index:100; width:600px; height:600px; display:none;
}

jQuery code:

$(document).ready(
    function() {

        // on click show div
        $('a.popup').click(
            function() {
                $('#dividname').fadeIn('slow');
            }
        }

    }
);

Upvotes: 4

Views: 3174

Answers (4)

CalebHC
CalebHC

Reputation: 5042

Try changing your style to this,

#dividname {

z-index:100; width:600px; height:600px;
position: fixed;
top: 50%;
left: 50%;

}

Hope this helps!

Edit:

Btw, here's a hack to get it to also work in IE6,

* html #dividname {
 position: absolute;
 top: expression((document.documentElement.scrollTop || document.body.scrollTop) +
 Math.round(17 * (document.documentElement.offsetHeight || document.body.clientHeight) /
 100) + 'px');
}

(Taken from the jqModal Style Sheet)

Upvotes: 1

Josh Mein
Josh Mein

Reputation: 28645

try this modal div for jquery

This tool will take care of the moving for you if the user scrolls

// to show
$.blockUI({ message: $('[id$=div]'),
    css: 
    {
        top: 50%;
        left: 50%;
        margin-top: -300px;
        margin-left: -300px;
    }
 });

// to hide                                    
$.unblockUI({ message: $('[id$=div]') });

Upvotes: 2

Alex
Alex

Reputation: 1594

In order to keep it centered with scrolling you will need to attach a function to move it to your scroll position.

You can do that with:

$(window).scroll(resize())

Get your current position with:

$(window).scrollTop();

This will comply with IE6 issues.

Upvotes: 0

Gumbo
Gumbo

Reputation: 655239

Try this:

#dividname {
    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -300px;
    margin-left: -300px;
    z-index: 100;
    width: 600px;
    height: 600px;
}

Where margin-top and margin-left is half of height and width respectively.

Upvotes: 4

Related Questions