问题
My example: http://jsfiddle.net/kwnk8qup/
My code:
<div id="container" style="position:relative;margin-top:50px;margin-left:50px;width:200px;height:300px;border: 2px solid red;">
<div id="container1" style="position:absolute;margin-top:130px;margin-left:30px;width:50px;height:50px;border: 2px solid #a1a1a1;">
</div>
</div>
The container
(parent div) position is relative container1
(child) position is absolute. I set the container2
top location as 130px
, it can be calculated from container
(parent div) top position but I need to show 130px
from document position. How to resolve with out changing positioning?
回答1:
I don't know if I got your question, but you could just move #container1
outside of the #container
so it would be relative to <body>
-element instead of #container
-element.
<body>
<div id="container" style="position:relative;margin-top:50px;margin-left:50px;width:200px;height:300px;border: 2px solid red;"></div>
<div id="container1" style="position:absolute;margin-top:130px;margin-left:30px;width:50px;height:50px;border: 2px solid #a1a1a1;"></div>
</body>
http://jsfiddle.net/q29ey2qt/
回答2:
Try Margin-top: -50px for the container1 and top:130px http://jsfiddle.net/30owkpv7/
Css
#container {
position:relative;
margin-top:50px;
margin-left:50px;
width:200px;
height:300px;
border: 2px solid red;
}
#container1 {
position:absolute;
margin-top:-50px; /*you need 130 from body (-50) of container */
top:130px; /*top from body*/
margin-left:30px;
width:50px;
height:50px;
border: 2px solid #a1a1a1;"
}
HTML
<div id="container">
<div id="container1"> </div>
</div>
来源:https://stackoverflow.com/questions/28712148/relative-absolute-positioning