In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

Max picture Max · Oct 5, 2012 · Viewed 380.2k times · Source

.offset([coordinates]) method set the coordinates of an element but only relative to the document. Then how can I set coordinates of an element but relative to the parent?

I found that .position() method get only "top,left" values relative to the parent, but it doesn't set any values.

I tried with

$("#mydiv").css({top: 200, left: 200});

but does not work.

Answer

Champ picture Champ · Oct 5, 2012

To set the position relative to the parent you need to set the position:relative of parent and position:absolute of the element

$("#mydiv").parent().css({position: 'relative'});
$("#mydiv").css({top: 200, left: 200, position:'absolute'});

This works because position: absolute; positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static).