0

Why in this snipped the scrollbar shows up?

I see that body is 100% tall as indicated by CSS, but it is not positioned at the top of the page. Instead, the margin from the h1 tag is pushing body down by that amount, resulting in the scrollbar because the body does not fit in the page.

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.root {
  height: 100%;
}
<div class='root'>
<h1>Test</h1>
</div>

My question is.. if the margin is in the h1 tag and h1 is inside body, why does body get pushed down and the scrollbar shows up?

Edy Bourne
  • 5,679
  • 13
  • 53
  • 101
  • 1
    https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing – epascarello Feb 13 '22 at 17:43
  • 1
    The thing is margin of H1 element is not "inside" the BODY but "hangs" above it. See margin collapsing: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing – myf Feb 13 '22 at 17:47
  • Ah, yes.. I usually don't hit that issue because the first element on a page doesn't usually have margins. Forgot about collapsing, thanks! – Edy Bourne Feb 13 '22 at 18:09

2 Answers2

0

You have a couple of options:

  1. set margin on h1 to 0
  2. set overflow to hidden on body
  3. remove height:100% from body and html

The snippet below does all three but any 1 will work

html, body {
  margin: 0;
  padding: 0;
  overflow:hidden;
 }
 
 

.root {
  height: 100%;
}

h1{margin:0;}
<div class='root'>
<h1>Test</h1>
</div>
DCR
  • 14,737
  • 12
  • 52
  • 115
0

It works the same if you delete height: 100%;

html, body {
  margin: 0;
  padding: 0; 
}

.root {
  height: 100%;
}
<div class='root'>
<h1>Test</h1>
</div>

Use the margin to position the H1 element.

Most programmers use the CSS * Selector.

  • The * selector selects all elements.
  • The * selector can also select all elements inside another element.
  • Read more information here.

Example:

html, body {
  margin: 0;
  padding: 0; 
}
*{
  margin: 0;
}
.root {
  height: 100%;
}
<div class='root'>
<h1>Test</h1>
</div>
In this case, all elements will have a margin: 0; It will work even if you leave height: 100%; the html and body.

And the last option, just like above, write a margin: 0; for each element.

html,
body {
  margin: 0;
  padding: 0; 
}

.root {
  height: 100%;
}

h1 {
  margin: 0;
}
<div class='root'>
<h1>Test</h1>
</div>
Sergiu
  • 356
  • 2
  • 10