margin推动body元素

margin推动body元素

本文介绍了CSS margin推动body元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为div元素设置了边距,但是body元素也获得了边距。

I'm setting a margin for a div element, however the body element also gets that margin.

请考虑以下代码:

<!-- 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:

到目前为止,通过向body元素添加 border:1px solid transparent; 属性来解决问题。这会破坏100%的高度,因为滚动条由于 1px 边框而出现。为什么会发生这种情况?

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?

可能解决方案(感谢您的帮助):添加 padding-top:1px margin-top:-1px ,这样100%的高度不会被滚动条损坏, / p>

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.

推荐答案

这听起来与我遇到的问题类似:。我解决了我的一个padding-top而不是一个边框,也许这与你的设计稍微更好一些?否则,请尝试此链接:

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 margin推动body元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 19:50