Reputation: 75
i need to position a div element at the center of the screen. I found a simple code below, but i need center of the ACTUAL screen, not "total height /2" of the page!
here is Jquery code that centers an element but not the actual screen;
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;}
as i said, i need to calculate the actual screen sizes (like 1366*768 or whatever users resized their browsers) and position the element at the center of the screen. so, if i scroll down the page, always the centered div should be at the center, again.
Upvotes: 7
Views: 23065
Reputation: 6304
If you're okay with using fixed
positioning instead of absolute
, you can use something like the following:
jQuery.fn.center = function ()
{
this.css("position","fixed");
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
$('#myDiv').center();
$(window).resize(function(){
$('#myDiv').center();
});
Demo: http://jsfiddle.net/GoranMottram/D4BwA/1/
Upvotes: 11
Reputation: 4318
it works..take this dive it as #sample
give its css style as
#sample{
margin-left:auto;
margin-right:auto;
width:200px;//your wish
}
think it works..
Upvotes: 1
Reputation: 2047
TRY THIS:
var width=$("#div").css("width");
var half=width/2;
$("#div").css("marginLeft","-"+half+"px");
Change #div with your selector.
Upvotes: 0