gpt4 book ai didi

html - css父div中不需要的边距

转载 作者:太空宇宙 更新时间:2023-11-04 14:13:09 25 4
gpt4 key购买 nike

我对解决这个问题感到沮丧,但无法解决它。

我有一个简单的 html 页面结构:

页眉 div、正文 div 和页脚 div。

问题是body div的内容(.form-container)影响了body div的margin 本身(.body-container)。

示例:

body {
margin: 0px;
}
.header-container {
height: 250px;
width: 100%;
background-color: red;
}
.body-container {
height: 500px;
width: 100%;
background-color: green;
background: #fff url('http://www.htmlcodetutorial.com/document/paper.gif') repeat scroll left top;
}
.footer-container {
height: 150px;
width: 100%;
background-color: blue;
}
.form-container {
margin-bottom: 30px;
margin-top: 30px;
}
<div class="header-container"></div>
<div class="body-container">
<div class="form-container"></div>
</div>
<div class="footer-container"></div>

如何去除正文 div 中的这个 margin

enter image description here

最佳答案

这是由于 margin 崩溃

这是预期的行为,Mozilla 开发者网络指出:

If there is no border, padding, inline content, or clearance to separate the margin-top of a block from the margin-top of its first child block, 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 its last child, then those margins collapse. The collapsed margin ends up outside the parent.

Mastering margin collapsing

在这种情况下,.body-container.form-container 满足条件,所以 .form 的 margin -container.body-container 之外结束。

你能做什么?

有很多方法可以阻止这种行为,但最简单的方法是在 .form-container 上使用 padding 而不是 margin > 因为 padding 不会折叠。

body {
margin: 0px;
}
.header-container {
height: 250px;
width: 100%;
background-color: red;
}
.body-container {
height: 500px;
width: 100%;
background-color: green;
background: #fff url('http://www.htmlcodetutorial.com/document/paper.gif') repeat scroll left top;
}
.footer-container {
height: 150px;
width: 100%;
background-color: blue;
}
.form-container {
padding: 30px 0;
}
<div class="header-container"></div>
<div class="body-container">
<div class="form-container"></div>
</div>
<div class="footer-container"></div>

关于html - css父div中不需要的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36444521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com