【问题标题】:Height 100% causes scroll bar to appear [duplicate]高度 100% 导致滚动条出现 [重复]
【发布时间】:2020-10-05 17:12:28
【问题描述】:

这个问题无处不在,解决方案总是一样的,但它对我从来没有用过,我不知道为什么!我只需要我的 div 填充整个视口而不创建滚动条。谁知道这会如此困难。每个人都说只需将 body 和 html 边距设置为零,但这不起作用。我还有一个垂直滚动条!我真的很沮丧,我真的很感激一些帮助。这是 JSFiddle https://jsfiddle.net/davdarobis/d3k4hv6q/23/

body, html {
  height: 100%;
  width: 100%;
  position: absolute;
  margin: 0;
}

#content
{
    height: 100%;
    border: solid blue 5px;
    margin: 0;
    
}

#heading {
  height: 40%;
  border: solid red 5px;
}

img {
  height: 100%;
}
<body>  

<div id="content">

    <div id="heading">
      <img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png" alt="" class="image">
    </div>

</div>


</body>

我不能使用 top: 0 bottom: 0 解决方案,因为这似乎搞砸了其子级的 height: 100% 属性。我完全被困住了。有任何想法吗?谢谢。

【问题讨论】:

  • 这可能是边界。
  • 尝试高度 100vh。这表明高度将是屏幕的 100 视图高度。
  • 你为什么要绝对的身体?
  • @ShioT 我也这么认为
  • 这是边界..解决阅读此box-sizing

标签: html css


【解决方案1】:

将属性box-sizing: border-box; 应用于所有元素(选择器*),这样由边框、填充和边距引起的额外空间将包含在 100% 中,而不是添加到 100%(即 100% + 5px 边框)。

* {
  box-sizing: border-box;
}

body, html {
  height: 100%;
  width: 100%;
  position: absolute;
  margin: 0;
}

#content
{
    height: 100%;
    border: solid blue 5px;
    margin: 0;
    
}

#heading {
  height: 40%;
  border: solid red 5px;
}

img {
  height: 100%;
}
<body>  

<div id="content">

    <div id="heading">
      <img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png" alt="" class="image">
    </div>

</div>


</body>

【讨论】:

    【解决方案2】:

    border: solid blue 5px; 导致滚动条出现。

    最终它的高度比父元素“body”高 10px(底部 5px + 5px 顶部)。

    如果你真的需要一个边框,你可以从 100% 中减去它。

    【讨论】:

    • 哦,哇,我一直认为边框是围绕容器内部而不是外部绘制的。这很有帮助!非常感谢!
    【解决方案3】:

    尝试向 html 标记添加一个溢出属性,如下所示:

    body, html {
      height: 100%;
      width: 100%;
      position: absolute;
      margin: 0;
      overflow-y: hidden;
    }
    

    【讨论】:

      【解决方案4】:

      尝试使用100vh 代替100%height 并为所有元素设置box-sizing:border-box;,我对css 做了一些更改,请检查它是否有效

      *{
        box-sizing:border-box;
       }
      body, html {
        height: 100vh;
        width: 100%;
        margin: 0;
        overflow:hidden;
      }
      
      #content
      {
          height: 100vh;
          border: solid blue 5px;
          margin: 0;
      
      }
      
      #heading {
        height: 40%;
        border: solid red 5px;
      }
      
      img {
        height: 100%;
      }
      

      希望它有效。

      【讨论】:

        【解决方案5】:

        将此行添加到您的 css 顶部,以防止滚动

        * {
          box-sizing: border-box;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-23
          • 2012-02-26
          • 2016-03-25
          • 2011-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多