Home » Design » CSS » Set “top,left” of an element with the position relative to the parent in jQuery

Set “top,left” of an element with the position relative to the parent in jQuery

posted in: CSS, Design, Javascript, jQuery, Programming 0

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

The.position() method get only “top,left” values relative to the parent, but it doesn’t set any values, so the following code doesn’t work:

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

Instead, to set the position relative to the parent, we need to set the position:relative of parent and position:absolute of the element, like in the following piece of code:

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

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


Just a reminder: set values correctly in jQuery!

In jQuery if the value passed is a string type, it must be followed by ‘px’ (i.e. ’90px’), where if the value is an integer, it will append the px automatically. The width and height properties are more forgiving (either type works). These are the main differences in the jQuery:

var x = "90";
var y = "120"
$(selector).css( { left: x, top: y } ); //does NOT work!
$(selector).css( { left: x + "px", top: y + "px" } ); //does work!

x = 90;
y = 120;
$(selector).css( { left: x, top: y } ); //does work!

Have fun in jQuery!


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.