I'm setting a margin for a div element, however the body element also gets that margin.
我为div元素设置了一个空白,但是body元素也有这个空白。
Consider this code:
考虑这段代码:
<!-- HTML -->
<body>
<div>
</div>
</body>
<!-- CSS -->
<style>
html,body {
height:100%;
margin:0;
padding:0;
outline:1px solid blue;
}
div {
margin:20px;
outline:1px solid red;
}
</style>
This is the result and the problem:
这就是结果和问题:
So far I've solved the problem by adding a border:1px solid transparent;
property to the body element. This ruins the 100% height because scrollbars appear due to the 1px
border. Why does this happen?
到目前为止,我已经通过增加边框解决了这个问题:1px固体透明;对主体元素的属性。这将破坏100%的高度,因为滚动条是由1px边框显示的。这为什么会发生?
POSSIBLE SOLUTION (thanks for the help): Add a padding-top:1px
and a margin-top:-1px
, this way the 100% height doesn't gets ruined with the scrollbars and your are avoiding margin collapsing.
可能的解决方案(感谢您的帮助):添加一个划板顶部:1px和一个边缘顶部:-1px,这样100%的高度不会因为滚动条而被破坏,你可以避免页边被折叠。
2 个解决方案
#1
3
This sounds similar to a problem I had: Margins and negative margins. I solved mine by putting a padding-top rather than a border, maybe this works with your design slightly better? Otherwise try this link: http://www.seifi.org/css/understanding-taming-collapsing-margins-in-css.html
这听起来很像我遇到的一个问题:边距和负边距。我解决了我的问题,把桨顶而不是边框,也许这和你的设计配合得更好?否则,请尝试此链接:http://www.seifi.org/css/- -in-css.html。
#2
2
This is caused by an effect known as collapsing margins.
这是由一种被称为“边缘崩溃”的效应引起的。
Certain adjoining margins combine to form a single margin. Those margins are said to “collapse.” Margins are adjoining if there are no nonempty content, padding or border areas or clearance to separate them.
某些相邻的边距合并成一个单一的边距。这些边际被称为“崩溃”。如果没有非空的内容、填充或边框区域或间隙将它们分隔开,则边距是相邻的。
http://www.w3.org/TR/css3-box/#collapsing-margins
http://www.w3.org/TR/css3-box/ collapsing-margins
#1
3
This sounds similar to a problem I had: Margins and negative margins. I solved mine by putting a padding-top rather than a border, maybe this works with your design slightly better? Otherwise try this link: http://www.seifi.org/css/understanding-taming-collapsing-margins-in-css.html
这听起来很像我遇到的一个问题:边距和负边距。我解决了我的问题,把桨顶而不是边框,也许这和你的设计配合得更好?否则,请尝试此链接:http://www.seifi.org/css/- -in-css.html。
#2
2
This is caused by an effect known as collapsing margins.
这是由一种被称为“边缘崩溃”的效应引起的。
Certain adjoining margins combine to form a single margin. Those margins are said to “collapse.” Margins are adjoining if there are no nonempty content, padding or border areas or clearance to separate them.
某些相邻的边距合并成一个单一的边距。这些边际被称为“崩溃”。如果没有非空的内容、填充或边框区域或间隙将它们分隔开,则边距是相邻的。
http://www.w3.org/TR/css3-box/#collapsing-margins
http://www.w3.org/TR/css3-box/ collapsing-margins