Talent Developer
Talent Developer

Reputation: 142

css position static element in relative element

I'm new to css.
I've some questions about position "static" and "relative". When the "static" element places in the "relative" one, how does the margin property work?
The code is following.

img {
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: -1;
}

.top{
  margin-top:20px;
  padding:20px;
 }
  
.back{
  background-color:#eee;
  position:relative;
}
<div class="back">
  <div class="top">Top text </div>
</div>

My question is that "top" div has the margin-top 20px.
The "back" div is "relative" and hasn't margin.
But why does "back" div have the margin same as the "top" div?


Upvotes: 2

Views: 194

Answers (1)

Michael Coker
Michael Coker

Reputation: 53674

What you're seeing is "margin collapse" https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

Parent and first/last child - If there is no border, padding, inline content, block_formatting_context created or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

Upvotes: 1

Related Questions