Skip to content Skip to sidebar Skip to footer

Jquery Position Div In Middle Of Page

Okay, so I have a div and I want to position it in the middle of a page. I've gotten so far $('#a').css('margin-top', '(document).height()/2 - ('#a').height()/2'); Is this correct

Solution 1:

**It shouldn't be in quotes. Also, you need to use the $() terminology. Try this:

$("#a").css('margin-top', $(document).height()/2 - $("#a").height()/2);

Or even better:

var $a = $("#a");
$a.css('margin-top', $(document).height()/2 - $a.height()/2);

Edit: Just to be clear, you can't put it in quotes because it will try to set the margin-top property literally to that string. Which is incorrect.

Solution 2:

I suggest you use .offset().

Description: Set the current coordinates of every element in the set of matched elements, relative to the document.

$("#a").offset({
   top: $(document).height()/2 -  $("#a").height()/2,
   left: $(document).width()/2 -  $("#a").width()/2
})

Solution 3:

This one worked for me & might help:

$('html, body').animate(
   {
   scrollTop: $('#your_div_id').offset().top-200
   }, 1000);

Change value 200 in 'top-200' to position your div as per your need..

Post a Comment for "Jquery Position Div In Middle Of Page"