此问题已经在这里有了答案:
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>
取消注释padding-top: 1px;
:https://jsfiddle.net/Yun93/uL6n5omg/6/
为什么添加padding-top
使空白消失?
我只是不希望在h1
中添加main
元素后跳出意外的空白。
我应该像上面那样使用padding-top
还是将h1
设置为margin-block-start: 0; margin-block-end: 0;
来实现?正确的方法是什么?
h1
的上边距与main
元素的上边距崩溃。
通过将顶部填充添加到main
元素,可以“停止”边距折叠。
More details on margin collapsing。影响您的特定代码段:
没有内容将父母与后代分开。如果没有边框,内边距,内联部分,创建的块格式上下文,或没有间隙来将一个块的边距顶部与其一个或多个子孙块的边距顶部分开;或没有边框,内边距,内联内容,高度,最小高度或最大高度来将一个块的边距底部与一个或多个后代块的边距底部分开,然后这些边距就会崩溃。折叠后的边距最终出现在父级之外。
查看此情况(或避免出现此情况的一种选择是从h1
中删除边距。例如:
h1 {
margin: 0;
font-size: 84px;
color: white;
}