Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: margin-top causes scrollbar

Tags:

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>
like image 921
Matthew Avatar asked Jul 30 '16 17:07

Matthew


People also ask

How do I change the scrollbar position in CSS?

We can use the CSS “::-webkit-scrollbar” property which is responsible for changing the shape, color, size, shade, shadow, etc. of the scroll bar. But, here the property which we will use is the direction property of CSS for changing the position of the scroll bar.

How do I scroll to the top in CSS?

window. scrollTo(0, 0); …is a sure bet to scroll the window (or any other element) back to the top.


2 Answers

That's because

  • h1 have some vertical margin by default, usually 0.67em.
  • The top margin of h1 collapses
  • height never includes the height of the margin area

Since the top margin of h1 collapses, it behaves like the margin belonged to the header instead of the h1. Since the content height of the h1 is 10%, its total height will be calc(10% + 0.67em).

That's why there is overflow.

If you remove the top margin but leave the bottom one there is no problem, because the bottom one does not collapse, due to the non-auto height. From Collapsing margins,

Two margins are adjoining if [...] both belong to vertically-adjacent box edges, [... e.g.]

  • top margin of a box and top margin of its first in-flow child
  • bottom margin of a last in-flow child and bottom margin of its parent if the parent has auto computed height.

So you can do any of the following

  • Remove h1's top margin
  • Prevent the margin collapse
  • Propose a box-sizing: margin-box to the CSS Working Group. It will probably be rejected.
like image 98
Oriol Avatar answered Sep 28 '22 12:09

Oriol


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/

like image 22
Michael Benjamin Avatar answered Sep 28 '22 13:09

Michael Benjamin