Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Which of the following jQuery function gets the top and left position values?

Description. The position( ) method gets the top and left position of an element relative to its offset parent.

Which jQuery method returns an element's position relative to the document?

jQuery position() Method The position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.

How do you position an element on top of another?

You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element. The z-index property determines the stacking order for positioned elements (i.e. elements whose position value is one of absolute , fixed , or relative ).

Which positioning property is used to set the element relative to its normal position?

An element with position: relative; is positioned relative to its normal position. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position.


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.


I found that 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).

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

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

Code offset dynamic for dynamic page

var pos=$('#send').offset().top;
$('#loading').offset({ top : pos-220});