Skip to content Skip to sidebar Skip to footer

Position Children Div Above Parent Div

I cant position div2 above div1 (not in the z-index but in vertical dimension). Negative position: top not workin

Solution 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.

Solution 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;
}
<divclass="oneDiv"><divclass="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.

Post a Comment for "Position Children Div Above Parent Div"