Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery position div in middle of page

Tags:

html

jquery

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?

like image 904
0x60 Avatar asked Dec 10 '22 11:12

0x60


2 Answers

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
})
like image 58
Reigel Avatar answered Jan 02 '23 04:01

Reigel


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

like image 41
Richard Marskell - Drackir Avatar answered Jan 02 '23 03:01

Richard Marskell - Drackir