50% 高度的 div 堆叠成行

50% height divs stacked as rows

我有 2 个高度为 50% 的 div 堆叠成一行,在一个分为 2 种颜色的页面上。

但是在较小的屏幕上用户需要滚动,这破坏了设计。我想让这两个 50% 的 div 填满整个网页。

.first-50 {
  height: auto;
  width: 100%;
  background: red;
  position: relative;
  color: #fff;
  min-height: 50%;
}

.second-50 {
  min-height: 50%;
  height: auto;
  width: 100%;
  background: blue;
  position: relative;
  display: none;
}
<div class="height-50 first-50">
  text
</div>
<div class="height-50 second-50">
  text
</div>

谢谢

您可以使用 vh 在视口调整大小时调整高度

引自w3schools.com

vw Relative to 1% of the width of the viewport
vh Relative to 1% of the height of the viewport

div {
    height: 50vh;
    width: 100%; /* or width : 100vw */
}

并添加你想要的任何内容

这是一个在我测试过的有限场景中工作的快速示例。

使用相对定位,它只会根据需要填充 space。您可能需要 absolute positioning/sizing 来强制它填充您需要的区域。但是,请注意页面上的其他元素(通常是相对的或默认的静态定位)根本不会意识到它们,而只会重叠它们或其他任何东西。

因此,如果您只是在寻找背景内容,无论顶部内容如何,​​它总是填充 50%/50%,这种绝对定位方法就足够了。如果您需要这两个区域来跟随页面的流动并尊重它们周围的元素,那么它不会。

body {
  height: 100%;
  min-height: 100%;
}

.first50 {
    background: red;
    color: #fff;
}

.second50 {
    top: 50%;
    background: blue;
    color: #fff;
}

.height50 {
    height: 50%;
    min-height: 50%;
    width: 100%;
    position: absolute;
}
<div class="height50 first50">
    text
</div>
<div class="height50 second50">
    text
</div>

根据之前用户的回答,使用 vh 是一种获取设备高度的方法,在现代浏览器中几乎完美支持。您可以将两个 div 拆分为 50vh,它会相应地调整大小。 CCS-Tricks 有更多关于此主题的信息!

.first-50 {
  height: 50vh;
  width: 100%;
  background: red;
  position: relative;
  color: #fff;
}

.second-50 {
  height: 50vh;
  width: 100%;
  background: blue;
  position: relative;
}
<div class="height-50 first-50">
  text
</div>
<div class="height-50 second-50">
  test
</div>