【问题标题】:div height calc(100% - 50px) not working [duplicate]div高度计算(100% - 50px)不起作用[重复]
【发布时间】:2018-04-30 16:49:41
【问题描述】:

https://codepen.io/joshuajazleung/pen/EbbgBN

<div class="outer">
  <div class="inner">
    <img src="https://placehold.it/300x200" alt="">
    <div>Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio animi harum impedit ex esse labore, placeat, tempore sapiente nisi cupiditate fugiat soluta ullam dicta ducimus accusamus tenetur consequuntur nesciunt earum!</div>
  </div>
</div>

.outer {
  background: red;
  position: relative;
  height: calc(100% - 60px);
}

.inner {
  position: relative;
  top: -100px;
}

由于 .inner 稍微移到顶部,为了减少 .outer 的整体空间,我使用了

height: calc(100% - 50px); // my logic is that it's div's height minus 50px

但它不起作用,想知道为什么?

【问题讨论】:

标签: css


【解决方案1】:
.outer {
  background: red;
  position: relative;
  height: calc(100vh - 50px);
}

尝试更改100% => 100vh

【讨论】:

    【解决方案2】:

    这不起作用,因为默认情况下 html 和 body 元素不会跨越整个高度。然后你在里面设置一个height: calc(100% - 50px);...为了简化它,只需设置height: 100%,你会发现它没有做你想做的事。

    您也可以将 body 和 html 的高度设置为 100%,或者您可以尝试使用 100vh 而不是 100%。

    【讨论】:

      【解决方案3】:

      不太清楚你在追求什么,但如果你使用包含百分比值的height 设置,则该元素的父元素 需要定义height 定义才能拥有百分比金额的参考。在你的例子中,这是body,它的父元素又是html元素,所以你应该添加这个CSS:

      html, body {
        height: 100%;
      }
      

      https://codepen.io/anon/pen/XzzNbN

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-06
        • 2014-02-16
        • 2014-08-07
        相关资源
        最近更新 更多