我试图在我的 .email-background 类和我的 .email-container 类之间一直围绕 .email-container 获得相同数量的空间。但是我在顶部和底部有更多的空间,即使我一直指定了 10px 的填充。我已尝试将这两个元素的边距归零。
`<style>
div {
padding: 0px;
margin: 0px;
}
.email-background{
background: gray;
padding: 10px
}
.email-container{
background: #ccf2ff;
}
.headerlogo {
margin-top: 30px;
border-radius: 30px;
border: 5px solid black;
max-width: 100%;
display: block;
margin: auto;
width: 50%;
margin-bottom: 40px;
}
.comcastlogo{
max-width: 100%;
display: inline;
float: left;
margin-left:
12%; margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="email-background">
<div class="email-container">
<h1>Here is your September 2017 GPA Maintenance Newsletter</h1>
<img src="https://i.imgur.com/5xskeoF.jpg" alt="The newsletter logo" class="headerlogo">
<img src="https://i.imgur.com/uhdSAow.jpg" alt="The comcast logo">
<h2 style="text-align: right; padding-right: 15%;">September 2017</h2>
</div>
</div>
</body> `
最佳答案
额外的填充来自 div 内的元素。要修复它,您只需要从第一个和最后一个元素中删除空格,即
- 移除第一个元素 (
<h1>
) 的顶部内边距和边距 - 移除最后一个元素 (
<h2>
) 的底部填充和边距
注意:不要只将 padding 和 margin 设置为 0,因为它会影响所有其他边的边距,这是您不想更改的!
CSS:
/* remove the space from the top of the h1 */
.email-background h1 {margin-top:0; padding-top:0}
/* remove the space from the bottom of the h2 */
.email-background h2 {margin-bottom:0; padding-bottom:0}
div {
padding: 0px;
margin: 0px;
}
.email-background {
background: gray;
padding: 10px
}
.email-container {
background: #ccf2ff;
}
.headerlogo {
margin-top: 30px;
border-radius: 30px;
border: 5px solid black;
max-width: 100%;
display: block;
margin: auto;
width: 50%;
margin-bottom: 40px;
}
.comcastlogo {
max-width: 100%;
display: inline;
float: left;
margin-left: 12%;
margin-bottom: 20px;
}
/* remove the space from the top of the h1 */
.email-background h1 {margin-top:0; padding-top:0}
/* remove the space from the bottom of the h2 */
.email-background h2 {margin-bottom:0; padding-bottom:0}
<div class="email-background">
<div class="email-container">
<h1>Here is your September 2017 GPA Maintenance Newsletter</h1>
<img src="https://i.imgur.com/5xskeoF.jpg" alt="The newsletter logo" class="headerlogo">
<img src="https://i.imgur.com/uhdSAow.jpg" alt="The comcast logo">
<h2 style="text-align: right; padding-right: 15%;">September 2017</h2>
</div>
</div>
为什么会这样?
这个问题来自于一种叫做“margin collapsing”的东西,其中 2 个相邻的垂直边距折叠到两个中的最高点。
边距折叠的详细解释见Mastering Margin Collapsing from Mozilla
关于html - 无法让 CSS 在顶部/底部提供与侧面相同的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379398/