问题描述
请参阅以下代码:
body {
height: 500px;
width: 80%;
margin-top: 0;
margin-bottom: 0;
margin-left: auto;
margin-right: auto;
padding: 0;
background-color: lightgray;
}
.header {
width: 80%;
height: 100px;
margin-left: auto;
margin-right: auto;
background-color: yellow;
/* border: solid 1px black; */
}
<div class="header">
<ul>
<li><a href="index.html">Dashboard</a></li>
</ul>
</div>
当我从.header中删除border: solid 1px black
时,我在div元素上方获得了一些空间.但是,当我添加border属性时,我得到了完美的结果(即删除了空格).边界财产对该空间有何影响?
When I remove border: solid 1px black
from .header I get some space above div element. But when I add the border property I get the perfect results (that is space removed). What should be impact of border property on this space?
推荐答案
This is due to margin collapsing (MDN, W3.org).
在您的示例中,header元素包含一个无序列表,默认情况下,该列表的顶部和底部都有页边距.由于边界折叠,它的边距被传输到页眉,而页眉又被传输到主体.结果,当标题和列表与主体的顶部对齐时,主体被向下推.
In your example the header element contains an unordered list which, by default, has a top and bottom margin. Because of border collapsing, its margin is transferred to the header which in turn is transferred to the body. As a result, the body is pushed down while the header and list aligns with the top of body.
添加边框是防止边距塌陷的一种方法(请参阅W3规格).如果要避免添加边框,请使用其他方法,例如将overflow: hidden
分配给标题.
Adding a border is one method to prevent margin collapsing (see W3 specs). If you want to avoid adding a border, use the other methods such as assign overflow: hidden
to the header.
body {
height: 500px;
width: 80%;
margin-top: 0;
margin-bottom: 0;
margin-left: auto;
margin-right: auto;
padding: 0;
background-color: lightgray;
}
.header {
width: 80%;
height: 100px;
margin-left: auto;
margin-right: auto;
background-color: yellow;
/*border: solid 1px black; */
overflow: hidden;
}
<div class="header">
<ul>
<li><a href="index.html">Dashboard</a></li>
</ul>
</div>
这篇关于边境财产对最高利润的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!