relative + absolute positioning

有些话、适合烂在心里 提交于 2020-01-16 18:16:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!