Fred Fred - 5 months ago 131x
Javascript Question

How to position a div dynamically below another?

I'm trying to use jQuery to detect the position of a div (

), so I can use that position to place another div (
) exactly below it. The right borders of the 2 divs are aligned (right border).

I'm trying to get the
bottom and right locations to use them as the
top and right borders. I've used this code, but it's not working. Any idea what I'm doing wrong?

var right = $('#olddiv').position().right;
var top = $('#olddiv').position().bottom;
$('#newdiv').css('top', right);
$('#newdiv').css('right', top);

Also, I'm not sure if
is what I need. I think this can be done with
, but I'm not sure:




I've used offset() to position elements dynamically. Try this:

var offset = $('#olddiv').offset();
var height = $('#olddiv').height();
var width = $('#olddiv').width();
var top = + height + "px";
var right = offset.left + width + "px";

$('#ID').css( {
    'position': 'absolute',
    'right': right,
    'top': top

also don't forget to bind this to the window.onresize event if you need it to scale when the user resizes the window.

UPDATE: another thought - does this have to be positioned absolutely? Why not just insert the div after the other in the DOM?


then just make sure they are the same width.