【问题标题】:div extending outside HTML and bodydiv 扩展到 HTML 和 body 之外
【发布时间】:2019-11-19 20:17:37
【问题描述】:

我有三个与中心对齐的 div,HTML 和正文区域延伸到窗口之外,以容纳最后一个还添加滚动条的 div。

我的代码

html,
body {
  margin: 0;
  border: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  position: relative;
}

p {
  margin: 0;
  padding: 0;
  border: 0;
}

.top {
  position: absolute;
  margin: 0;
  padding: 0;
  left: 50%;
  top: 0%;
  transform: translate(-50%, 0%);
}

.center {
  position: absolute;
  margin: 0;
  padding: 0;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.bottom {
  position: absolute;
  margin: 0;
  padding: 0;
  left: 50%;
  top: 100%;
  transform: translate(-50%, -0%);
}
<html>

<head>
  <title>Position</title>
</head>

<body>
  <div class="container">

    <div class="top">
      <p>I am top div</p>
    </div>

    <div class="center">
      <p>I am center div</p>
    </div>

    <div class="bottom">
      <p>I am bottom div</p>
    </div>

  </div>


</body>

</html>

【问题讨论】:

    标签: html css


    【解决方案1】:

    这是在页面底部执行此操作的绝对定位,您将页脚绝对放置在top:100%seems to cause overflow 通过将元素扩展到body 的边界之外。

    我注意到top:95% 上的.bottom“修复”了这个问题。

    但更简单的解决方案是只使用 flexbox,因为这种情况就是它的用途,而且它方式的工作量更少:

    body,
    html {
      margin: 0;
      padding: 0;
    }
    
    .container {
      height: 100vh;
    }
    
    .container {
      display: flex;
      flex-direction: column; /*specifies main axis to be vertical*/
      justify-content: space-between; /*main axis positioning*/
      align-items: center; /*cross axis (horizontal) positioning*/
    }
    <html>
    
    <head>
      <title>Position</title>
    </head>
    
    <body>
      <div class="container">
    
        <div class="top">
          <p>I am top div</p>
        </div>
    
        <div class="center">
          <p>I am center div</p>
        </div>
    
        <div class="bottom">
          <p>I am bottom</p>
        </div>
    
      </div>
    
    </body>
    
    </html>

    【讨论】:

    • 感谢您的回答。我从来没有使用过弹性。我从来不知道有这样的财产存在
    • 没问题 - 我编辑了我的代码 sn-p,它比我做的更简单(从将整个 .center div 弯曲到 100% 高度,而是只使用 justify-content:space-between on容器)。一旦你使用 flex box 进行布局,你就再也回不去了......
    猜你喜欢
    • 2013-02-10
    • 2012-10-02
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 2014-05-20
    • 1970-01-01
    • 2019-08-20
    相关资源
    最近更新 更多