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.
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.
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();
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.
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.
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/
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With