Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position a div element at the center of the ACTUAL screen? (JQuery)

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.

like image 445
Said Bahadır Kaya Avatar asked Feb 26 '13 13:02

Said Bahadır Kaya


People also ask

How do you position a div in the middle of the screen?

To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.

How do I center a div using jQuery?

There is a way to center a <div> element to the middle of a page using only jQuery. To use the above function, you should choose the <div> element to center and pass it through your new function: $(element). center();

How do I center a div using JavaScript?

js | center() Function. The center() function is used to set the alignment of element into the center either vertically, horizontally, or both, relative to its parent element or according to the body if the element has no parent.

What does position () method do in jQuery?

jQuery position() Method The position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.


2 Answers

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/

like image 110
Goran Mottram Avatar answered Sep 23 '22 01:09

Goran Mottram


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

like image 22
sasi Avatar answered Sep 22 '22 01:09

sasi