Home > OS >  Why does setting p element's vertical margins to 1 px make scrollbars appear?
Why does setting p element's vertical margins to 1 px make scrollbars appear?

Time:12-29

p element without margin:

body {
  width: 100vw;
  height: 100vh;
  margin: 0;
}

p {
  margin: 0 0;
}
<!DOCTYPE html>
<html>

<body>
  <p>p</p>
</body>

</html>

p element with margin:

body {
  width: 100vw;
  height: 100vh;
  margin: 0;
}

p {
  margin: 1px 0;
}
<!DOCTYPE html>
<html>

<body>
  <p>p</p>
</body>

</html>

Why does setting p tag's vertical margin to 1px make scrollbars appear?

CodePudding user response:

Margin collapse. The p's top margin collapses with the body's margin, making the body's margin box height 100vh 1px, which overflows the viewport, requiring the scrollbars.

If you stop the margin from collapsing by setting the body's display to flow-root, the scrollbars disappear.

body {
  width: 100vw;
  height: 100vh;
  margin: 0;
  display:flow-root;
}

p {
  margin: 1px 0;
}
<!DOCTYPE html>
<html>

<body>
  <p>p</p>
</body>

</html>

CodePudding user response:

p's are block-level which generate line breaks both before and after the element when in the normal flow. This allows for content to flow above or beneath instead of adjacent.

When you add margin to this it creates a collapsed margin.

When you use inline-block the element generates one or more inline element boxes that do not generate line breaks before or after themselves. In normal flow, the next element will be on the same line if there is space.

So when you set p to display: inline-block; the scrollbar is removed.

body {
  width: 100vw;
  height: 100vh;
  margin: 0;
}

p {
  margin: 1px 0;
  display: inline-block;
}
<!DOCTYPE html>
<html>

<body>
  <p>p</p>
</body>

</html>

  • Related