Position children div above parent div

心不动则不痛 提交于 2019-12-25 01:56:11

问题


<div id="1">
 <div id="2">
 </div>
</div>

I cant position div2 above div1 (not in the z-index but in vertical dimension). Negative position: top not working, seems like top border of parent div is limit for childrens.

      |-------|
      | div2  |
------|       |
|     |_______|
|          |
|   div1   |
|__________|      

回答1:


Class names starting with digits are not valid, although it may work in some browsers. Use div1 or div2 and that should work. Take a look at this answer for a good explanation of valid CSS class names.

Update after comments:

Ok, well, without seeing the offending code, it's hard to see where the problem is. But using this css you can reproduce your diagram:

#div2 {
    position:relative;
    top:-30px;
    left:100px;
}

As I think you already know.. but maybe you forgot the position:relative? Anyway, see it working in this fiddle.




回答2:


Remember that the position: relative attribute allows the children within that element to be place relative to that element. It essentially defines a new point by which elements can be placed, relatively.

So if we have a div (oneDiv), with position: relative, and then another div (twoDiv) within that div, that has position: absolute, then the second div (twoDiv) will be positioned absolutely, but relative to its parent.

.oneDiv {
  position: relative;
  top: 100px;
  background-color: red;
  height: 200px;
  width: 200px;
}

.twoDiv {
  position: absolute;
  right: -50px;
  top: -50px;
  background-color: blue;
  height: 100px;
  width: 100px;
}
<div class="oneDiv">
  <div class="twoDiv">
  </div>
</div>

As such, "top" is no longer the top of the document, but the top of the childs parent. By using the above example, you can ensure you keep your layout, and if you move .oneDiv, regardless, twoDiv will follow with it.



来源:https://stackoverflow.com/questions/7866804/position-children-div-above-parent-div

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