How to place a div element in the center of the ACTUAL screen? (Jquery)

I need to put a div element in the center of the screen. I found a simple code below, but I need the center of the ACTUAL screen, not the "total height / 2" page!

here is the jQuery code that centers the 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 (for example, 1366 * 768 or any other users who have resized their browsers) and place the element in the center of the screen. therefore, if I scroll down the page, the always centered div should again be in the center.

+7
source share
3 answers

If you use 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/

+10
source

it works .. do this dive as #sample

specify css style as

 #sample{ margin-left:auto; margin-right:auto; width:200px;//your wish } 

I think it works.

+1
source

TRY IT:

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

Change #div to your selector.

0
source

All Articles