开发者

How to setup absolute position of a DIV with Jquery?

开发者 https://www.devze.com 2023-03-16 01:46 出处:网络
I have a code like that: $(\'#lol\').css({ position: \"absolute\", marginLeft: 0, marginTop: 0, top: 0, left: 0});

I have a code like that:

$('#lol').css({ position: "absolute",

        marginLeft: 0, marginTop: 0,

        top: 0, left: 0});

The problem is that my div 开发者_JAVA百科is positioned relatively, so it is point 0 of a div rather than the entire window. Why is that?


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号