views:

672

answers:

5

Hey,

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');
            }
        }

    }
);
+3  A: 

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.

Gumbo
Likely the simplest solution. However, won't work in IE6, not sure about newer IEs.
Jani Hartikainen
Ya, `position: fixed` doesn't work until ie7, maybe only 8
Justin Johnson
Position: absolute. That will center the div just fine in all a-grade browsers (IE 6 and above included).
roosteronacid
A: 

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.

Alex
+1  A: 

Hello,

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)

CalebHC
A: 

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]') });
jmein
Thanks, I have used many of their plugins before. Works great!
Will Ayers
A: 

Try this: How to center a DIV on the page with Javascript

Josh Stodola