Matthew Matthew - 4 months ago 22
HTML Question

css: margin-top causes scrollbar

The

h1
element causes a scrollbar to appear. Can anyone explain me why?



html, body {
margin: 0;
padding: 0;
height: 100%;
}
header {
height:10%;
}
section {
height:90%;
}

<header>
<h1>
Hello
</h1>
</header>
<section>
test
</section>




Answer

Because the h1 comes with a margin, applied by the default style sheet.

When you add this margin (often margin-top: .67em and margin-bottom: .67em) to the height: 100% in your code, this exceeds the viewport height, launching a vertical scroll bar.

Give the h1 a margin: 0.

Whether you use box-sizing: content-box or border-box, the margin space will always be added to your height declaration.

If you want to add space around your h1 without adding height, use padding instead of margin, along with box-sizing: border-box. Here are some implementation options: https://css-tricks.com/box-sizing/

Comments