I am having a div, which should be centre of the window, even after scrolling. How to achieve it
http://www.flickr.com/photos/41695354@N08/4496376638/
You can do this by setting the display property to “flex.” Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.
You can do it with a fixed width positioned in center and with negative margins with half of the width and half of the height. So for a div with id your_div
that is 200x200 in size, you'd do:
#your_div {
width: 200px;
height: 200px;
position: fixed;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
I was looking this up myself and this post came up first. With further research I found this link instead which I think is the best cross browser solution:
Using jQuery to center a DIV on the screen
Basically to use jquery to overcome the IE6 issues just take the $(window).scrollTop() and $(window).scrollLeft() into consideration.
Hope this helps.
Steve
I suggest the following solution:
1) In JS when you want to show a window:
{
var width = $(window).width();
var heigth = $(window).height();
var myWindow = $('.my-window');
myWindow .show('fast');
myWindow .offset(
{
left: (width - myWindow .width()) / 2 + $(window).scrollLeft(),
top: (heigth - myWindow .height()) / 2 + $(window).scrollTop()
});
}
2) in CSS: .my-window
{
position: fixed;
}
If you have to support IE 6 then you have to append the div element to the body and set the position as "absolute". Make the position attribute of the body element as "relative". And apply the rest of the styles suggested by reko_t. That should keep the div in the center as you scroll.
Apart from that, I would suggest you to consider one more case when you want to position some div in the center of the page. If your viewport's size is smaller than the div which you are positioning in the center then as you scroll you'll end up seeing the same portion of the div until you resize the window to be bigger than that of the div.
To solve this case, you should go for a javascript solution rather than a pure css solution. You should define a window resize listener. If the resized window's viewport is smaller then position the div in the left-top corner of the viewport and disable the onscroll listener. If the resized window's viewport is bigger than the div then your onscroll listener should apply the styles suggested by reko_t.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With