【问题标题】:Adding padding-top makes separate elements stick together [duplicate]添加 padding-top 使单独的元素粘在一起[重复]
【发布时间】:2020-01-25 04:00:56
【问题描述】:

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会使空白消失?


我只是不希望在main 中添加h1 元素后跳出的意外空白。

我应该像上面一样使用padding-top 还是将h1 设置为margin-block-start: 0; margin-block-end: 0; 来实现?正确的方法是什么?

【问题讨论】:

    标签: css


    【解决方案1】:

    h1 的上边距与 main 元素的上边距折叠。

    通过将顶部填充添加到 main 元素,“停止”边距折叠。

    More details on margin collapsing。影响您的具体 sn-p:

    没有分离父母和后代的内容。 如果没有边框、内边距、内联部分、创建的块格式化上下文,或者没有将块的边缘顶部与其一个或多个后代块的边缘顶部分开的间隙;或者没有边框、填充、内联内容、高度、最小高度或最大高度来将块的边距底部与其一个或多个后代块的边距底部分开,然后这些边距折叠。折叠的边距最终在父级之外。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-20
      • 2017-06-25
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-24
      • 2013-12-10
      • 1970-01-01
      相关资源
      最近更新 更多