CSS 边距推动 body 元素
我为 div 元素设置了边距,但是 body 元素也获得了该边距。
考虑这段代码:
<!-- 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>
这是结果和问题:
到目前为止,我已经通过添加 border:1px Solid transparent;
属性。这会破坏 100% 的高度,因为由于 1px
边框而出现滚动条。为什么会发生这种情况?
可能的解决方案(感谢您的帮助):添加 padding-top:1px
和 margin-top:-1px
,这样 100 % height 不会被滚动条破坏,并且您正在避免边距折叠。
I'm setting a margin for a div element, however the body element also gets that margin.
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?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这听起来类似于我遇到的问题:边距和负边距。我通过放置顶部填充而不是边框解决了我的问题,也许这更适合您的设计?否则请尝试此链接: http://www.seifi .org/css/understanding-taming-collapsing-margins-in-css.html
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.w3.org/TR/css3-box/#collapsing -边距
This is caused by an effect known as collapsing margins.
http://www.w3.org/TR/css3-box/#collapsing-margins
我知道这是一个老问题,但我只是想指出,在问题给出的示例中,可以使用填充而不是边距:
I know this is an old question, but I just wanna point out that, in the example given in the question, one could use padding instead of margins: