-1

Apply this code and you can see it. The margine-top of the internal box is applied to the outside. How can inBox not affect the box?

<!DOCTYPE html>
<html>
<head>
  <style>
.box{
  width: 400px;
  height: 400px;
  background-color: red;
}
.inBox{
  width: 200px;
  height: 200px;
  background-color: white;

  margin-top: 100px;
}
  </style>
  <meta charset="utf-8">
</head>
<body>
  <div class = "box">
    <div class = "inBox">
  </div>
</body>
</html>
Kunj
  • 1,822
  • 21
  • 31
L. kiju
  • 25
  • 3
  • That's how `margin` works; `margin` pushes the target element away from its *parent*. Are you sure you're not looking for `padding`, which pushes the target element's *content* away from *the element*? – Obsidian Age May 28 '19 at 04:05
  • 2
    [When to use margin vs padding in CSS](https://stackoverflow.com/questions/2189452/when-to-use-margin-vs-padding-in-css) –  May 28 '19 at 04:05

2 Answers2

0

You can’t do margins inside an element. You can use padding. If you don’t want the padding to affect the side of the box, also set box-sizing: border-box.

Vertical margins have some unintuitive characteristics, like collapsing. There are ways to prevent vertical margin collapse that may solve your issue.

ray hatfield
  • 16,302
  • 4
  • 25
  • 21
0

So you actually can have margin-top on the child element. As mentioned by others, vertical margins can collapse. This is one of the least intuitive instances, where the margin-top of the child is apparently going right through the parent.

You can counter this by adding any amount of padding to the parent. I added 1px of padding-top and the margin suddenly appears to behave as originally expected:

.box {
  width: 400px;
  height: 400px;
  background-color: red;
  padding-top: 1px;
}

.inBox {
  width: 200px;
  height: 200px;
  background-color: white;
  margin-top: 100px;
}
<div class="box">
  <div class="inBox">.inBox has margin-top</div>
</div>

As recommended by others I would also probably just use padding-top on the parent to create all of the space but this trick exposes an interesting nuance of margin collapse.

BugsArePeopleToo
  • 2,797
  • 1
  • 12
  • 14