简体   繁体   English

当容器大于视口时,将高度设置为浏览器视口的100%?

[英]Set height to 100% of browser viewport when container is bigger than viewport?

I'm working on a website and I need to set a div's height and width to cover the entire area of the browser viewport like many modern websites. 我正在网站上工作,我需要设置div的高度和宽度,以覆盖浏览器视口的整个区域,就像许多现代网站一样。 However, I can't simply set its height to 100% because its parent element is another div whose height must be set to bigger than the browser window. 但是,我不能简单地将其高度设置为100%,因为它的父元素是另一个div,其高度必须设置为大于浏览器窗口。 Is there another way of doing this? 还有另一种方法吗?

Here's a code sample set up similar to my website. 这是一个与我的网站类似的代码示例。

HTML HTML

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

CSS CSS

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

5.1.2. 5.1.2。 Viewport-percentage lengths: the 'vw', 'vh', 'vmin', 'vmax' units 视口百分比长度:'vw','vh','vmin','vmax'单位

The viewport-percentage lengths are relative to the size of the initial containing block. 视口百分比长度相对于初始包含块的大小。 When the height or width of the initial containing block is changed, they are scaled accordingly. 当初始包含块的高度或宽度改变时,它们相应地缩放。

Use viewport-percentage lengths. 使用视口百分比长度。 In this case, 100vh . 在这种情况下, 100vh

.contentBox {
    height: 100vh;
}

Updated Example 更新的示例


You can also use calc() to subtract the 10px top/bottom margins: 您还可以使用calc()减去10px上/下边距:

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

Updated Example 更新的示例

..it's just worth pointing out that you need to establish a new block formatting context on the parent element in order to prevent the collapsing margins . ..这是值得指出的,你需要在父元素上建立一个新的块格式化上下文 ,以防止折叠边距

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM