Javascript centering div on page

For javascript, I use the jQuery structure, but I can easily integrate any javascript functions into it. I have a problem: I have a div that disappears when I click the link. How can I make it align to the center of the page and stay even while scrolling.

Below is an example of what I have just 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'); } } } ); 
+4
source share
4 answers

try modal div for jquery

This tool will take care of the move 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]') }); 
+2
source

Try the following:

 #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 are half the height and width respectively.

+4
source

Try changing your style,

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

Hope this helps!

Edit:

Btw, here hack it so that it also works 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'); } 

(Adapted from the jqModal stylesheet)

+1
source

To keep it in the center with scrolling, you will need to attach a function to move it to the scroll position.

You can do it with

 $(window).scroll(resize()) 

Get current position with

 $(window).scrollTop(); 

This will be consistent with IE6 issues.

0
source

All Articles