so how do set the left and top..(even when i scroll the scrollBar)
thanks
machine elf and Stefan Kendall are both very close but both incomplete so you just combine each as so (machine elf didn't account for scrollbars and Setfan didn't account for the height and width of the div itself):
Assuming your id for your div is "myDiv"
$('#myDiv').css('position','fixed');
$('#myDiv').css("left", ($(window).width()/2-$('#myDiv').width()/2) + "px");
$('#myDiv').css("top", ($(window).height()/2-$('#myDiv').height()/2) + "px"));
You may also need to set the css of your div to a fix height and width and its display is set to "block". You can do this with JQuery as well.
Also, you can combine all these into one long string.
You should be able to take @wag2639's code and put it in a function form like what @machine elf suggested then set the window scroll handler so the object stays centered as the user scrolls the page.
$(window).scroll(function () {
$("#your_obj").center();
});
This answer isn't jQuery, but I've seen a CSS trick where you can set position:relative; left:-50%
on an outer element and setting the reverse position:relative; left:50%
on the inner element to center. I typically prefer to accomplish these tasks using CSS whenever possible.
See http://www.pmob.co.uk/pob/centred-float.htm for details.
If you need dead center...
$('#myDiv').css('position','absolute');
$('#myDiv').css("left", ($(window).width()/2-$('#myDiv').width()/2) + "px");
$('#myDiv').css("top", ($(window).height()/2-$('#myDiv').height()/2) + "px"));
Something like that should work. This is all untested. You would want to tie this to the window resize, too.
Looks like this should do it: Center element plugin
there is also this question w/ some answers: CSS: Center a float:left element based on screen width?
This list of other jQuery tricks also has an answer (#17): 20 Top jQuery tips & tricks for jQuery programmers
I'm not sure what you mean, but if you want a fixed element when scrolling use the CSS position: fixed;
(which you can apply in jQ with $('#myDiv').css('position','fixed');
, then set top and left) or see:
What is the simplest jQuery way to have a 'position:fixed' (always at top) div?
jQuery.fn.center = function () {
var w = $(window);
this.css("position","fixed");
this.css("top",w.height()/2-this.height()/2 + "px");
this.css("left",w.width()/2-this.width()/2 + "px");
return this;
}
$("#your_obj").center();