开发者

Javascript position two elements on top of each other

开发者 https://www.devze.com 2022-12-08 04:22 出处:网络
I have two divs one above the other. The second on is absolutely positioned below it (an abso开发者_如何转开发lute div inside a relative div).

I have two divs one above the other. The second on is absolutely positioned below it (an abso开发者_如何转开发lute div inside a relative div).

I want to move the second div on top of the other div, so it appears in the middle.

The procedure for this is to set the style.top of DIV2 to be the same as DIV1, this should in theory position it on top of it. However so far attempts have failed.

The absolute positioning is working correctly, because putting in values moves it correctly, but I think I am using the wrong way to get the height/top values of DIV1.

Ideas?

I tried this:

divLoading.style.top = divContent.style.top;

but it stays where it was.

Edit: The problem isn't how absolute/relative works but which javascript values are the correct ones to use. Using DIV2.style.top = DIV2.style.top - DIV1.clientHeight moves it to the top... but clientHeight is not correct, because if DIV1 changes size, it moves DIV2 way too far upwards.

Edit: offsetTop seems to be zero.


An absolute positioned div inside a relative positioned one, will by default 'borrow' it's top and left position from the relative parent. That means that by setting left:0; top:0 the divs will share the same position.

If you want to move the second div up, you will have to set a negative top (i.e. top: -200px). The top and left properties are relative to the base position, not the body (unless the div isn't in a relative positioned parent, in which case the body is the base position)


If div1 is positioned relative, then the top and left values will move the div relative to where it would have been in the normal flow. So style.top = 10 would move it 10 pixels down from its normal position.

If the position was "absolute", the style.top = 10 would move the div to 10 pixels down from the div it is being positioned relative to (ie, a previous element that had position: relative, or the body of the document)

0

精彩评论

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