【问题标题】:100% height goes a few pixels off the page?100% 高度离开页面几个像素?
【发布时间】:2015-12-03 12:42:26
【问题描述】:

我正在尝试将一个框设置为页面的 100% 高度。但是在 Chrome 和 IE 中,以下内容从页面底部延伸了几个像素,所以我必须滚动。为什么?为什么这里有滚动条?

  <!doctype html>
  <html >
  <head>
    <style type="text/css">
        html, body 
        {
            margin: 0px;
            padding: 0px;
            height: 100%; 
        }
        div {
            border:5px solid black;
            height: 100%;
        }
    </style>
  </head>
  <body >
    <div >This flows a few pixels off the bottom of the page</div>
  </body>
</html>

【问题讨论】:

    标签: html css


    【解决方案1】:

    它会离开页面几个像素,因为您包含 5 像素的边框。 div 的主体是页面高度的 100%,但 border 位于其外部,在 100% 高度旁边为页面增加了 10px 的总高度。因此,在 1000 像素的页面上,您的 div 的高度将为 1010 像素。去掉边框,它的高度就完全正确了。

    div {
        height: 100%;
    }
    

    如果您仍然想要边框,但不需要多余的高度,您可以使用box-sizing: border-box 属性将其放置在 div 的边界内

    div {
        height: 100%;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        -webkit-box-sizing: border-box;
    }
    

    【讨论】:

    • 如果您想要边框,请将其添加到 div 内,而不是在其边缘,使用以下命令:stackoverflow.com/questions/9601357
    • @PauloAvelar 谢谢,已更新以反映您的添加
    【解决方案2】:

    ...这是您的另一种选择:

    html,body 
    {
        height:100%;
        margin:0;
        padding:0
    }
    div
    {
        border:5px solid black;
        display:block;
        height:-moz-calc(100% - 10px);
        height:-webkit-calc(100% - 10px);
        height:calc(100% - 10px);
        width:calc(100% - 10px)
    }
    

    享受吧!

    【讨论】:

      【解决方案3】:

      您可以通过为所有主流浏览器声明border-box 属性来保持当前设置为5px 边框:

      div
      {
          height:100%;
          box-sizing:border-box !important;
          -moz-box-sizing:border-box !important;
          -webkit-box-sizing:border-box !important;
      }
      

      由于您要处理 100% 的 div 大小,因此强烈建议添加 !important,这样您就不会与其他属性发生任何冲突。

      【讨论】:

        猜你喜欢
        • 2013-05-05
        • 1970-01-01
        • 1970-01-01
        • 2014-11-24
        • 2014-07-08
        • 1970-01-01
        • 1970-01-01
        • 2013-11-10
        • 2010-10-17
        相关资源
        最近更新 更多