-2

Container is pulled down when inner element puts top margin so white section appear at the top of page. How can i prevent that white section ?

.container {
  background: red;
  height: 500px;
}

.inner {
  margin-top: 100px;
  height: 50px;
  background: yellow;
}
Why there is white section in here ??
<div class="container">
  <div class="inner"></div>
</div>
Freshblood
  • 6,285
  • 10
  • 59
  • 96

3 Answers3

2

Set the overflow to auto on the outer element. You're seeing collapsing margins in your example

Parent and first/last child - If there is no border, padding, inline part, 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.

.container {
  background: red;
  height: 500px;
  overflow: auto;
}

.inner {
  margin-top: 100px;
  height: 50px;
  background: yellow;
}
Why there is white section in here ??
<div class="container">
  <div class="inner"></div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
0

The result you are getting is expected due to the CSS Box Model.

The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.

Explanation of the different parts of the Box Model:

Content - The content of the box, where text and images appear

Padding - Clears an area around the content. The padding is transparent

Border - A border that goes around the padding and content

Margin - Clears an area outside the border. The margin is transparent

See the difference between margin and padding illustrated in this snippet:

.container {
  background: red;
  height: 500px;
}

.inner {
  height: 50px;
  background: yellow;
}

.margin {
  margin-top: 100px;
}

.padding {
  padding-top: 100px;
}
<div class="container">
  <div class="inner margin">
    Inner div has a margin-top
  </div>
</div>
<hr>
<div class="container">
  <div class="inner padding">
    Inner div has a padding-top
  </div>
</div>
<hr>
<div class="container">
  <div class="inner">
    Inner div has no padding/margin
  </div>
</div>
mmshr
  • 937
  • 1
  • 7
  • 9
0

Remove the margin-top:100px on the div .inner

You can also use margin-top: 0; , or top:0; but it is not necessary...

DEMO

Try this:

html,body {margin:0}

.container {
background: red;
height: 500px;
}

.inner {
/*margin-top: 100px;*/
/*margin-top: 0;*/
/*top:0;*/
height: 50px;
background: yellow;
}

// ---------------      

<div class="container">
  <div class="inner"></div>
</div>
Pablo_Web
  • 423
  • 2
  • 14