I have a code like that:
$('#lol').css({ position: "absolute",
marginLeft: 0, marginTop: 0,
top: 0, left: 0});
The problem is that my div is positioned relatively, so it is point 0 of a div rather than the entire window. Why is that?
Absolute Positioning You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document. Move Left - Use a negative value for left. Move Right - Use a positive value for left. Move Up - Use a negative value for top.
jQuery position() MethodThe 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.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.
As pointed out in the other answers, at least one of the parent element of #lol
has a position
set, that causes your element to be positioned within the parent.
A solution with jQuery would be to attach the element directly to body.
$('#lol').css({
position: "absolute",
marginLeft: 0, marginTop: 0,
top: 0, left: 0
}).appendTo('body');
This will make it to appear top left of the window.
Why is that?
If you want to use position: absolute
relatively to the entire window, you need to make sure that your #lol
has no parent elements also positioned absolute
, fixed
, or relative
.
Otherwise, any positioning you specify will take place relative to them.
Elements that have position: relative
or position: absolute
will be positioned relative to the closest parent that has position: relative
or position: absolute
. So, if you want your element to be positioned relative to the entire window, keep it outside of any parent wrappers with relative or absolute positions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With