1

header {
background-color: grey;
height: 118px;
text-align: center;
}

nav {
background-color: red;
height: 40px;
}

main {
background-color: blueviolet;
height: 400px;
text-align: center;
/*Why adding padding-top makes the white space disappear?*/
/*padding-top: 1px; */
}

footer {
background-color: green;
height: 100px;
}

.container {
width: 1024px;
margin: 0 auto;
}

h1 {
font-size: 84px;
color: white;
}

p {
font-size: 16px;
color: white;
}

/* * {
margin-block-start: 0;
margin-block-end: 0;
margin-inline-start: 0;
margin-inline-end: 0;
} */
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<style>

</style>
</head>

<body>
<div class="container">
 <header>
  <p>Header</p>
 </header>

 <nav>


 </nav>

 <main>
  <h1>let's meat</h1>
  <p>We love sharing good food with great people. We bring over 30 years industry experience and passion to Adare. With a dishes that are carefully designed to bring you a truly satisfying Irish food experience that you are sure to remember. 
  </p>
 </main>

 <footer>

 </footer>
</div>

</body>

</html>

Uncomment padding-top: 1px;:
https://jsfiddle.net/Yun93/uL6n5omg/6/

Why adding padding-top makes the white space disappear?


I just don't want the unexpected white space which jumps out after I adding the h1 element inside main.

Should I use padding-top like above or set h1 to margin-block-start: 0; margin-block-end: 0; to achieve that? What's the proper way?

Rick
  • 7,007
  • 2
  • 49
  • 79

1 Answers1

5

The h1's top margin is collapsing with the main element's top margin.

By adding the top padding to the main element, that "stops" the margin collapsing.

More details on margin collapsing. The specific snippet that is affecting you:

No content separating parent and descendants. If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks; or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of one or more of its descendant blocks, then those margins collapse. The collapsed margin ends up outside the parent.

One option to see this (or avoid it) is to remove the margin from the h1. For example:

h1 {
    margin: 0;
    font-size: 84px;
    color: white;
}
skovy
  • 5,430
  • 2
  • 20
  • 34