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

.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.

This question is related to jquery css jquery-selectors positioning css-position

The answer is


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).


Refreshing my memory on setting position, I'm coming to this so late I don't know if anyone else will see it, but --

I don't like setting position using css(), though often it's fine. I think the best bet is to use jQuery UI's position() setter as noted by xdazz. However if jQuery UI is, for some reason, not an option (yet jQuery is), I prefer this:

const leftOffset = 200;
const topOffset = 200;
let $div = $("#mydiv");
let baseOffset = $div.offsetParent().offset();
$div.offset({
  left: baseOffset.left + leftOffset,
  top: baseOffset.top + topOffset
});

This has the advantage of not arbitrarily setting $div's parent to relative positioning (what if $div's parent was, itself, absolute positioned inside something else?). I think the only major edge case is if $div doesn't have any offsetParent, not sure if it would return document, null, or something else entirely.

offsetParent has been available since jQuery 1.2.6, sometime in 2008, so this technique works now and when the original question was asked.


Code offset dynamic for dynamic page

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

Use offset() function of jQuery. Here it would be:

$container.offset({
        'left': 100,
        'top': mouse.y - ( event_state.mouse_y - event_state.container_top ) 
    });

$("#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

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to positioning

jQuery position DIV fixed at top on scroll CSS transition effect makes image blurry / moves image 1px, in Chrome? How can I fill a div with an image while keeping it proportional? In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document? sizing div based on window width Make div stay at bottom of page's content all the time even when there are scrollbars How to position the div popup dialog to the center of browser screen? How do I center an SVG in a div? CSS: Position text in the middle of the page Stopping fixed position scrolling at a certain point?

Examples related to css-position

How does the "position: sticky;" property work? How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? CSS z-index not working (position absolute) Relative div height How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport? How to position the Button exactly in CSS How to make fixed header table inside scrollable div? Absolute positioning ignoring padding of parent Have a fixed position div that needs to scroll if content overflows How to make div fixed after you scroll to that div?