问题描述
我正在为 div 元素设置边距,但是 body 元素也会获得该边距.
考虑这个代码:
<身体><div>
<!-- CSS --><风格>html,正文{高度:100%;保证金:0;填充:0;轮廓:1px 纯蓝色;}div {边距:20px;轮廓:1px纯红色;}</风格>
这是结果和问题:
到目前为止,我已经通过向 body 元素添加 border:1px solid transparent;
属性解决了这个问题.这会破坏 100% 的高度,因为 1px
边框会出现滚动条.为什么会发生这种情况?
可能的解决方案(感谢您的帮助):添加一个 padding-top:1px
和一个 margin-top:-1px
,这滚动条不会破坏 100% 的高度,并且您可以避免边距折叠.
这听起来与我遇到的问题相似:边距和负边距.我通过放置填充顶部而不是边框来解决我的问题,也许这对您的设计更有效?否则试试这个链接:http://www.seifi.org/css/understanding-taming-collapsing-margins-in-css.html
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.
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
这篇关于CSS 边距推动 body 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!