【问题标题】:Set height to 100% of browser viewport when container is bigger than viewport?当容器大于视口时,将高度设置为浏览器视口的 100%?
【发布时间】:2015-01-18 07:00:00
【问题描述】:

我正在开发一个网站,我需要设置一个 div 的高度和宽度,以覆盖浏览器视口的整个区域,就像许多现代网站一样。但是,我不能简单地将其高度设置为 100%,因为它的父元素是另一个 div,其高度 必须 设置为大于浏览器窗口。还有另一种方法吗?

Here's 类似于我的网站设置的代码示例。

HTML

<div class="entireThing">
  <div class="contentBox">
  </div>
  <div class="contentBox">
  </div>
</div>

CSS

.entireThing {
    height: 8000px;
    width: 100%;
}
.contentBox {
    height: 100%; /*This works only if parent is same size as window*/
}

【问题讨论】:

    标签: html css layout


    【解决方案1】:

    5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

    视口百分比长度与初始包含块的大小有关。当初始包含块的高度或宽度发生变化时,它们会相应地缩放。

    使用视口百分比长度。在这种情况下,100vh

    .contentBox {
        height: 100vh;
    }
    

    Updated Example


    您还可以使用calc() 减去10px 顶部/底部边距:

    .contentBox {
        height: calc(100vh - 20px); /* Subtract the 10px top/bottom margins */
        margin: 10px;
        color: white;
        background-color: #222;
    }
    

    Updated Example

    ..值得指出的是,您需要在父元素上建立a new block formatting context才能prevent the collapsing margins

    【讨论】:

    • 哇!我不敢相信我以前从未听说过这个。谢谢!
    • 注意:- 周围需要空格,但你怎么知道要减去多少?我试过html, head, body, { margin: 0px;},但还是太大了。
    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 2016-09-07
    • 2014-09-08
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多