为什么从div中删除边框会破坏我的布局?

use*_*845 6 css border

我有一个粘性页脚的网站,我想在我的contentContainer顶部有一个背景图片.边框很好,但如果我从内容"薄蓝色固体"删除边框整个事情被推下来,我的背景图像不再在顶部...

<div id="mainContain">
    <div id="header"></div>     
    <div id="contentContain">
        <div id="content">
            <h2>Hog</h2>
        </div>  
    </div>
    <div id="footer"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

我的CSS是:

html, body {
  padding: 0;
  margin: 0;
  height: 100%;
}
#mainContain {
    min-height: 100%;
    position:relative;
}

#header {
    width: 100%;
    height: 180px;
    background-color: #111111;
}

#contentContain {
    background-image: url('../img/shadow-bg.png');
    background-position: center top;
    background-repeat: no-repeat;
    padding-bottom: 45px;   /* This value is the height of your footer */
}

#content {
    margin: auto;
    border: thin blue solid;
}

#footer {
      position: absolute;
      Width: 100%;
      bottom: 0;
      height: 45px;  /* This value is the height of your footer */
      background-color: #111111;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*det 11

您可能会看到折叠边距的结果.

您可以通过在块元素的顶部添加边框或一些填充来防止边距折叠,或者通过设置创建新的块格式化上下文来阻止边距折叠overflow: auto,例如:

#content {
    margin: auto;
    border: thin transparent solid; /* option 1 */
    padding-top: 1px; /* option 2 */
    overflow: auto; /* option 3 */
}  
Run Code Online (Sandbox Code Playgroud)

使用哪个选项

如果使用前两个选项,则可以通过边框宽度或填充向块元素的顶部添加额外的1px高度.

使用的第三个选项overflow不会影响元素的高度.

前两个选项可能向后兼容除最原始浏览器之外的所有选项.任何支持CSS2.1的东西都会按预期工作.

至于overflow它,除了一些小的例外,它一直受到IE4的广泛支持.有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/CSS/overflow.