I am using negative margin on bottom to pull the adjacent element to overlap current element. It is my intention to make it overlap. But I want the whole div to be overlappe
In your sample code, both elements share the same stacking context.
That being the case, the rules which define how elements are layered are defined in the spec as follows: (bold is mine)
Within each stacking context, the following layers are painted in back-to-front order:
- the background and borders of the element forming the stacking context.
- the child stacking contexts with negative stack levels (most negative first).
- the in-flow, non-inline-level, non-positioned descendants.
- the non-positioned floats.
- the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
- the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
- the child stacking contexts with positive stack levels (least positive first).
So you can see that - within the same stacking context - inline-level elements (#5) are painted above non-inline-level elements (#3)
So in your case - since both the <img>
and the <div>
share the same stacking context and the <img>
element is an inline-level element - it is painted above the <div>
- even though the <div>
occurs later in the document tree order.
Check out this codepen demo which illustrates this point further
Extra reading:
Elaborate description of Stacking Contexts
Stacking without z-index (MDN)
Z-Index And The CSS Stack: Which Element Displays First?
Position: relative will solve your issue of overlapping
<style>
.div1 {
background-color: black;
position: relative;
}
img {
margin-bottom:-20px;
}
</style>