我有一个包含两列的布局-左div和右div。

右侧的div具有灰色背景色,我需要它根据用户浏览器窗口的高度垂直展开。现在,背景色结束于该分区中的最后一段内容。

我尝试过高度:100%,最小高度:100%;,等


当前回答

这是一个高度修正。

在CSS中使用:

#your-object: height: 100vh;

对于不支持vh单元的浏览器,请使用modernizr。

添加此脚本(为vh单元添加检测)

// https://github.com/Modernizr/Modernizr/issues/572
// Similar to http://jsfiddle.net/FWeinb/etnYC/
Modernizr.addTest('cssvhunit', function() {
    var bool;
    Modernizr.testStyles("#modernizr { height: 50vh; }", function(elem, rule) {
        var height = parseInt(window.innerHeight/2, 10),
            compStyle = parseInt((window.getComputedStyle ?
                      getComputedStyle(elem, null) :
                      elem.currentStyle)["height"], 10);

        bool = !!(compStyle == height);
    });
    return bool;
});

最后,如果浏览器不支持vh单位,请使用此函数将视口的高度添加到#your object:

$(function() {
    if (!Modernizr.cssvhunit) {
        var windowH = $(window).height();
        $('#your-object').css({'height':($(window).height()) + 'px'});
    }
});

其他回答

实际上,对我最有效的是使用vh属性。

在我的React应用程序中,我希望即使调整大小,div也能与页面高度匹配。我尝试了高度:100%;,溢出-y:自动;,但在设定高度时,它们都不起作用:(你的百分比)vh;它按预期工作。

注意:如果您正在使用填充、圆角等,请确保从vh属性百分比中减去这些值,否则会增加额外的高度并显示滚动条。这是我的示例:

.frame {
  background-color: rgb(33, 2, 211);
  height: 96vh;
  padding: 1% 3% 2% 3%;
  border: 1px solid rgb(212, 248, 203);
  border-radius: 10px;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: 50px 100px minmax(50px, 1fr) minmax(50px, 1fr) minmax(50px, 1fr);
}

如果你能绝对定位你的元素,

position: absolute;
top: 0;
bottom: 0;

会做到这一点。

现在使用高度:100vh;对于固定的窗口高度:

<style>
    .header-top {
        height: 100vh;
        background: #000;
        color: #FFF;
        display: flex;
        align-items: center;
        padding: 10px;
        justify-content: space-around;
    }

    .header-top ul {
        list-style: none;
        padding: 0;
        margin: 0;
        display: flex;
        align-items: center;
    }

    .header-top ul li {
        padding:0px 10px;
    }
</style>

<div class="header-top">
    <div class="logo">Hello</div>
    <ul>
        <li>Menu</li>
        <li>About Us</li>
        <li>Contact US</li>
        <li>Login</li>
    </ul>
</div>

有几种方法可用于将<div>的高度设置为100%。

方法(A):

html,正文{高度:100%;最小高度:100%;}.div左{高度:100%;宽度:50%;背景:绿色;}.div右{高度:100%;宽度:50%;背景:灰色;}<div class=“div left”></div><div class=“div right”></div>

方法(B)使用vh:

html,正文{高度:100%;最小高度:100%;}.div左{高度:100vh;宽度:50%;背景:绿色;浮动:左侧;}.div右{高度:100vh;宽度:50%;背景:灰色;浮动:右侧;}<div class=“div left”></div><div class=“div right”></div>

方法(c)使用挠性箱:

html,正文{高度:100%;最小高度:100%;}.包装器{高度:100%;最小高度:100%;显示:柔性;}.div左{宽度:50%;背景:绿色;}.div右{宽度:50%;背景:灰色;}<div class=“wrapper”><div class=“div left”></div><div class=“div right”></div></div>

如果要设置<div>或任何元素的高度,也应该将<body>和<html>的高度设置为100%。然后可以将元素的高度设置为100%:)

下面是一个示例:

body, html {
  height: 100%;
}

#right {
  height: 100%;
}