Vonder
Vonder

Reputation: 4059

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?

Upvotes: 6

Views: 26960

Answers (5)

chandanjha
chandanjha

Reputation: 931

If you want to use absolute:position on an element relative to the entire window screen than any parent of that element should not given any position values like absolute,fixed or relative,because the element will take the position relative to its parent if any position attribute is given to it. Hope it answer you well...:)

Upvotes: 0

Wex
Wex

Reputation: 15695

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.

Upvotes: 3

DanielB
DanielB

Reputation: 20230

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.

Upvotes: 20

user801985
user801985

Reputation: 423

That's just how positioning works. If you have any parent elements with any position specified the absolute positioning will happen relative to them.

If you want it to the window but can't do away with any of the other elements' positioning you'll need to remove the item from regular page flow either manually or with a bit of JS.

Upvotes: 0

Pekka
Pekka

Reputation: 449435

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.

Upvotes: 3

Related Questions