2

I have two div elements and nav > nav_1. When i add a margin-top:20px; to nav, nav goes down 20pxaccording to body which is correct.
But when i add this margin-top:20px;to nav_1,nav_1 goes down 20px with nav according to body.
why ? nav_1 element of nav and it should move according to nav.
In that question im looking for an explanation

.nav {
  height: 500px;
  width: 500px;
  background-color: black;
  margin-top:50px;
}
.nav .nav_1 {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin-top:50px;
}
<div class="nav">
  <div class="nav_1">
  </div>
</div>
Prajwal Shrestha
  • 524
  • 3
  • 12

3 Answers3

4

This is one case of "margin collapse" mechanism. In brief margin of parent and child elements are collapsed into single margin of size equals max of their corresponding margins. There are several ways to disable such a behaviour, e.g. adding border or padding to parent element. You can read more about that mechanism at mdn article.

Paul Kozlovitch
  • 786
  • 7
  • 12
2

You can use padding on nav and remove margin on .nav .nav_1

or

you can add display:inline-block in .nav .nav_1

 .nav {
  height: 500px;
  width: 500px;
  background-color: black;

}
.nav .nav_1 {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin-top:20px;
  display:inline-block;
}
<div class="nav">
  <div class="nav_1">
  </div>
</div>
Mukul Kant
  • 7,074
  • 5
  • 38
  • 53
-1

Further to @Paul Kozlovitch answer, to fix this you can set the the parent display:inline-block (or float etc).

.nav {
  height: 500px;
  width: 500px;
  background-color: black;
  margin-top:50px;
  display:inline-block;
}
.nav .nav_1 {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin-top:50px;
}
<div class="nav">
  <div class="nav_1">
  </div>
</div>
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135