添加padding-top使单独的元素粘在一起

Ric*_*ick 1 css

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;
} */
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

取消注释padding-top: 1px;https :
//jsfiddle.net/Yun93/uL6n5omg/6/

为什么添加padding-top会使空白消失?


我只是不希望在添加h1元素后突然跳出空白main

我应该使用padding-top像上面或组h1margin-block-start: 0; margin-block-end: 0;实现呢?正确的方法是什么?

sko*_*ovy 5

h1的上边距与崩溃main元素的上边距。

通过在main元素上添加顶部填充,可以“停止”边距折叠。

有关保证金崩溃的更多详细信息。影响您的特定代码段:

没有内容将父代和后代分开。 如果没有边框,内边距,内联部分,创建的块格式上下文,或者没有清除以将一个块的边距顶部与其一个或多个子孙块的边距顶部分开;或没有边框,填充,内联内容,高度,最小高度或最大高度来将一个块的边距底部与一个或多个后代块的边距底部分开,然后这些边距就会崩溃。折叠的边距最终在父级之外。

看到(或避免出现)的一种选择是从中删除边距h1。例如:

h1 {
    margin: 0;
    font-size: 84px;
    color: white;
}
Run Code Online (Sandbox Code Playgroud)