我有两个div:
<div id="headercontainer" data-type="background" data-speed="5">
<div id="headersubcontainer">
<h1>Simple and Cost Effective Web Solutions</h1>
</div>
</div>
<div id="teamcontainer" data-type="background" data-speed="5">
<div id="teamsubcontainer">
<h1>Developed by a dedicated team</h1>
</div>
</div>
两者都有 100% 的宽度和 800 像素的高度。第一个标题我设置了 top-margin: 160px。它没有将标题向下移动到其父 div 中,而是将父 div 向下移动,如您在这张图片中所见:
这是我的相关CSS:
h1{
font-size: 48px;
font-family: $header-font-stack;
font-weight: 100;
width: 400px;
}
#headercontainer{
width: 100%;
height: 800px;
background-image: image-url("background.jpg");
background-position: center top;
background-repeat: no-repeat;
}
#headercontainer h1{
text-align: center;
margin: 0px auto;
margin-top: 160px;
color: #610B21;
}
使用填充显然有效,但我想更恰本地使用边距。如何在不移动容器的情况下设置上边距并将标题向下移动到容器中?
最佳答案
这是由于 margin collapsing :
Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.
这导致父元素反向继承子元素的上边距。
你可以通过在子元素前添加
来防止这种情况
Demo Fiddle
....或将以下任何一项应用于父级:
- float :左/右
- position:absolute
- 显示:内联 block
将 display:inline-block;
添加到父级可能是首选,如果它的宽度设置为 100%
Demo Fiddle
关于html - 为什么设置此子元素的上边距会将其父容器向下推?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23788169/