<html>, <body>, padding, margin, 100vh and calc ()

Consider the following code snippet:

html {
  margin: 0;
  padding: 0;
  background-color: blue;
}

body {
  margin: 0;
  padding: 0;
  background-color: green;
  min-height: 100vh;
}
<section style="min-height: 50px; background-color: pink;"></section>
Run codeHide result

As expected, the body element fills the entire viewport with green, and on top is the section element in pink.

Now suppose you want to do something very simple, for example, set a field in the section element : style="min-height: 50px; background-color: pink; margin-bottom: 10px;", Suddenly, a blue bar from the html element appears at the bottom of the viewport.

html {
  margin: 0;
  padding: 0;
  background-color: blue;
}

body {
  margin: 0;
  padding: 0;
  background-color: green;
  min-height: 100vh;
}
<section style="min-height: 50px; background-color: pink; margin-bottom: 10px;"></section>
Run codeHide result

Question 1) Why is this behavior? That doesn't make sense to me.

One way to fix this behavior is to include the min-heightbody element in addition to the padding and calc () elements:

html {
  margin: 0;
  padding: 0;
  background-color: blue;
}

body {
  margin: 0;
  padding: 0;
  padding-bottom: 1px;
  background-color: green;
  min-height: calc(100vh - 1px);
}
<section style="min-height: 50px; background-color: pink; margin-bottom: 10px;"></section>
Run codeHide result

However, this decision requires such a trick that I do not feel comfortable.

2 ? ( : )

+4
3

margin-collapsing. , , , , , .

:

() , ( , ), , .

:

/

10px , , min-height:100vh

html {
  margin: 0;
  padding: 0;
  background-color: blue;
}

body {
  margin: 0;
  padding: 0;
  background-color: green;
  min-height: 100vh;
}
<section style="min-height: 50px; background-color: pink;margin-bottom: 10px;"></section>
Hide result

, . , , , , box-sizing:border-box, calc.

html {
  margin: 0;
  padding: 0;
  background-color: blue;
}

body {
  margin: 0;
  padding: 0;
  background-color: green;
  min-height: 100vh;
  border-bottom:1px solid transparent;
  /* OR padding-bottom:1px */
  box-sizing:border-box;
}
<section style="min-height: 50px; background-color: pink;margin-bottom: 10px;"></section>
Hide result

flex, flex ( ):

html {
  margin: 0;
  padding: 0;
  background-color: blue;
}

body {
  margin: 0;
  padding: 0;
  background-color: green;
  min-height: 100vh;
  display:flex;
  flex-direction:column;
}
<section style="min-height: 50px; background-color: pink;margin-bottom: 10px;"></section>
Hide result

, :

https://css-tricks.com/what-you-should-know-about-collapsing-margins/

?

CSS margin;

, flexbox

+1

, , margin-bottom margin-top .

-2

I also don’t know why this behavior, but you can try with the following CSS to overcome this situation:

body {margin: 0; padding: 0; background-color: green; position:absolute; left:0; top:0; right:0; bottom:0; overflow:auto;}
-2
source

Source: https://habr.com/ru/post/1692336/


All Articles