In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?
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
).
$("#mydiv").css('top', 200);
$("#mydiv").css('left', 200);
You could try jQuery UI's .position method.
$("#mydiv").position({
of: $('#mydiv').parent(),
my: 'left+200 top+200',
at: 'left top'
});
Check the working demo.