JQuery middle position page div

Ok, so I have a div, and I want to place it in the middle of the page. I still

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

Is it correct?

+3
source share
3 answers

** This should not be in quotation marks. In addition, you need to use terminology $(). Try the following:

$("#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: To be clear, you cannot put it in quotation marks because it will try to set the margin-top property literally on this line. This is not true.

+7
source

I suggest you use .offset().

Description: Set the current coordinates of each 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
})
+7

:

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

200 'top-200', div .

0

Source: https://habr.com/ru/post/1791111/


All Articles