【问题标题】:Incorrect positioning of divs when using height in percentage使用百分比高度时 div 的定位不正确
【发布时间】:2017-03-09 06:07:44
【问题描述】:

我不确定这个问题之前有没有发过,但是我不知道如何有效地问这个问题。

在我的网站中,我一个接一个地创建了两个大的部分(不是指标签),一个的高度设置为 100%,另一个设置为 90%。我在第二部分的正下方添加了一个 div。为了保持 div 卡住,我将“top”设置为 190%,以模拟两个部分的长度。虽然我已经为每个部分设置了一个最小高度,当它们停止调整大小时,这会使 div 在这些部分下方爬行。

在对元素使用“位置:绝对”时如何避免这种情况?

html 示例(使用更大的部分):

<html>
    <body>
        <div class="section1"></div>
        <div class="box"></div>
    </body>
</html>

css 示例:

.section1 {
    display: inline-block; width: 100%; height: 100%; min-height: 500px;
    position: absolute;
}
.box {
    width: 100%; height: 200px;
    position: absolute; top: 100%; margin-top: 50px;
}

谢谢,

乔纳森

【问题讨论】:

    标签: html css position css-position margin


    【解决方案1】:

    只是不要使用position:absolute

    我假设您拥有它的原因是因为您需要 100% 的视口高度,而不使用 JS。您可以使用vh 单元,但它没有最好的支持/可靠性。

    最简单的方法是简单地将htmlbody 设置为height:100%;

    body,
    html {
      margin: 0;
      height: 100%;
    }
    .full {
      height: 100%;
      background: teal;
    }
    .shorter {
      height: 90%;
      background: #fbfbfb;
    }
    footer {
      background: #222021;
      color: white;
      text-align: center;
      padding: 10px;
    }
    <section class="full"></section>
    <section class="shorter"></section>
    <footer>Made with love by a kitten</footer>

    请注意,我确实为样式添加了额外的 CSS。

    【讨论】:

    • @JonathanFogelström np,很高兴我能帮上忙:D
    猜你喜欢
    • 2017-05-01
    • 2017-09-28
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2016-09-16
    • 2013-01-23
    • 1970-01-01
    • 2015-08-30
    相关资源
    最近更新 更多