【问题标题】:CSS margin pushing the body elementCSS边距推动body元素
【发布时间】:2011-12-06 06:18:00
【问题描述】:

我正在为 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>

这是结果和问题:

到目前为止,我已经通过向 body 元素添加 border:1px solid transparent; 属性解决了这个问题。这会破坏 100% 的高度,因为滚动条是由于 1px 边框而出现的。为什么会这样?

可能的解决方案(感谢您的帮助):添加 padding-top:1pxmargin-top:-1px,这样滚动条不会破坏 100% 的高度,并且您可以避免边距折叠.

【问题讨论】:

  • 最佳解决方案可能是在父级上添加overflow:auto;,正如@Chris Nicholson 提供的链接中所述

标签: html css layout margins


【解决方案1】:

这听起来类似于我遇到的问题:Margins and negative margins。我通过放置一个填充顶部而不是边框​​来解决我的问题,也许这对你的设计稍微好一点?否则试试这个链接:http://www.seifi.org/css/understanding-taming-collapsing-margins-in-css.html

【讨论】:

    【解决方案2】:

    这是由称为折叠边距的效果引起的。

    某些相邻的边距组合成一个边距。这些利润被称为“崩溃”。如果没有非空内容、填充或边界区域或间隙来分隔它们,则边距是相邻的。

    http://www.w3.org/TR/css3-box/#collapsing-margins

    【讨论】:

      【解决方案3】:

      我知道这是一个老问题,但我只想指出,在问题给出的示例中,可以使用填充而不是边距:

      <!-- HTML -->
      <body>
        <div>
          content
        </div>
      </body>
      
      <!-- CSS -->
      <style>
        html, body {
          box-sizing: border-box; /* padding makes part of the */
          height: 100%;           /*  box whose height is 100% */
          margin: 0;
          padding: 0;
          outline: 1px solid blue;
        }
        
        body {
          padding: 20px;
        }
        
        div {
          outline: 1px solid red;
        }
      
      </style>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-19
        • 1970-01-01
        • 2013-11-09
        • 2014-02-07
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多