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

标签 html css layout

我在网站上工作,我需要设置一个 div 的高度和宽度来覆盖浏览器视口(viewport)的整个区域,就像许多现代网站一样。但是,我不能简单地将其高度设置为 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*/
}

最佳答案

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

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.

使用视口(viewport)百分比长度。在本例中,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 - 当容器大于视口(viewport)时,将高度设置为浏览器视口(viewport)的 100%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005190/

相关文章:

javascript - 如何在 Canvas 中绘制虚线矩形?

css - 网站的风格取决于季节

html - 设置表格的最大宽度

html - 列表中图像旁边的最小 css/html 文本段落

android - 几乎填满整个屏幕的 map fragment

html - 为什么:only-of-type require a different HTML tag?

javascript - 点击时 Fancybox 加载 div?

css - 网格布局 : create CSS so Elements keep position when adjacent element gets resized

android - Android Studio 布局上的 YoutubePlayer 错误

html - 边距不适用于 div、表格和其他父元素