Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup absolute position of a DIV with Jquery?

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?

like image 692
Vonder Avatar asked Jun 28 '11 10:06

Vonder


People also ask

How do you move an absolute position in a div?

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.

How do I set relative position in jQuery?

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.

How do you apply position absolute?

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.

Can a div be position absolute and relative?

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.


3 Answers

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.

like image 88
DanielB Avatar answered Nov 10 '22 07:11

DanielB


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.

like image 36
Pekka Avatar answered Nov 10 '22 07:11

Pekka


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.

like image 23
Wex Avatar answered Nov 10 '22 07:11

Wex