我想让主体有100%的浏览器高度。我可以用CSS来做吗?

我试着设置高度:100%,但它不起作用。

我想为页面设置一个背景色来填充整个浏览器窗口,但如果页面内容很少,我就会在底部得到一个丑陋的白色条。


当前回答

我设计了div容器-通常是主体的唯一子元素,带有以下css

.body-container {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
}

其他回答

如果你想保持正文的边缘,不想要滚动条,使用下面的css:

html { height:100%; }
body { position:absolute; top:0; bottom:0; right:0; left:0; }

设置body {min-height:100%}将为您提供滚动条。

参见http://jsbin.com/aCaDahEK/2/edit?html,output上的演示。

如果需要,你也可以使用JS

var winHeight = window.innerHeight    || 
document.documentElement.clientHeight || 
document.body.clientHeight;

var pageHeight = $('body').height();
if (pageHeight < winHeight) {
    $('.main-content,').css('min-height',winHeight)
}

这里更新

html
  {
    height:100%;
  }

body{
     min-height: 100%;
     position:absolute;
     margin:0;
     padding:0; 
}

对于真正的纯粹主义者来说,这种方法尊重浏览器的默认边距,并防止由其他方法产生的不需要的滚动,除了随着内容的增长而增长。在Chrome, Safari和Firefox中测试。背景只是做做样子……

html { 显示:flex; flex-direction:列; 高度:100%; 背景:红色; } 身体{ flex: 1; 背景:绿色; }

在20多个答案之后,似乎没有一个人提到了我发现的最关键的因素——标记。

在尝试了这个问题和其他一些问题的基本每个答案之后,我重新构造了我的标记,如下所示:

<body>
  <div class="section1">
    <nav>
    </nav>
    ...
  </div>
  <div class="section2">
  </div>
</body>

本质上,它需要两个不同的外部容器。第一个容器用于包含导航栏,并将背景色/图像一直扩展到浏览器的高度,第二个容器用于包含“折叠以下”的所有内容——包括第二个背景色/图像。

这个解决方案允许第一个容器的背景一直扩展到底部,同时保持第二个容器的自由,以占用尽可能多的空间。

从这一点开始,唯一需要得到我和原始问题想要的结果的CSS如下:

body {
  height: 100%;
}

.section1 {
  height: 100%;
  background: black; /* for demo purposes */
}

.section2 {
  background: white; /* for demo purposes */
}