7

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.

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
  • [This answer](http://stackoverflow.com/questions/504052/determining-position-of-the-browser-window-in-javascript) might get you going in the right direction. It's quite an old thread so I'm sure there's some nice library that wraps up the different calls required for the different browsers – Matt Feb 26 '13 at 13:38
  • @Matt There was a comment saying that IE now accepts screenX and screenY. So now its cross browser compatible. :) – Pedro Estrada Feb 26 '13 at 13:40

3 Answers3

11

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/

Goran Mottram
  • 6,244
  • 26
  • 41
1

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..

sasi
  • 4,192
  • 4
  • 28
  • 47
  • If you read carefully, the question is about VERTICAL centering, and you're proposing HORIZONTAL centering. – Havok Mar 24 '14 at 19:53
0

TRY THIS:

var width=$("#div").css("width");
var half=width/2;
$("#div").css("marginLeft","-"+half+"px");

Change #div with your selector.

harikrishnan.n0077
  • 1,927
  • 4
  • 21
  • 27
  • Again... If you read carefully, the question is about VERTICAL centering, and you're proposing HORIZONTAL centering. – Havok Mar 24 '14 at 19:54