得到div占据100%的身高,减去固定高度的页眉和页脚

Ric*_*ard 72 css

从我的研究来看,这似乎是一个绝对经典的CSS问题,但我无法找到明确的答案 - 所以StackOverflow就是这样.

如何设置内容div占据身高的100%,减去固定高度页眉和页脚占用的高度?

<body>
  <header>title etc</header>
  <div id="content">body content</div>
  <footer>copyright etc</footer>
</body>

//CSS
html, body { 
  height: 100%;
}
header { 
  height: 50px;
}
footer { 
  height: 50px;
}
#content { 
  height: 100% of the body height, minus header & footer
}
Run Code Online (Sandbox Code Playgroud)

我想使用纯CSS,并且答案是跨浏览器的防弹.

Pet*_*ete 55

这个版本将在所有最新的浏览器和IE8工作,如果你有Modernizr的脚本(如果不只是改变headerfooterdivS):

小提琴

html,
body {
  min-height: 100%;
  padding: 0;
  margin: 0;
}

#wrapper {
  padding: 50px 0;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

#content {
  min-height: 100%;
  background-color: green;
}

header {
  margin-top: -50px;
  height: 50px;
  background-color: red;
}

footer {
  margin-bottom: -50px;
  height: 50px;
  background-color: red;
}

p {
  margin: 0;
  padding: 0 0 1em 0;
}
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
  <header>dfs</header>
  <div id="content">
  </div>
  <footer>sdf</footer>
</div>
Run Code Online (Sandbox Code Playgroud)

滚动内容: 小提琴


agr*_*boz 38

只要它不是跨浏览器解决方案,您可能会利用使用calc(expression)来实现这一点.

html, body { 
 height: 100%;
}
header {        
 height: 50px;
 background-color: tomato
}

#content { 
 height: -moz-calc(100% - 100px); /* Firefox */
 height: -webkit-calc(100% - 100px); /* Chrome, Safari */
 height: calc(100% - 100px); /* IE9+ and future browsers */
 background-color: yellow 
}
footer { 
 height: 50px;
 background-color: grey;
}
Run Code Online (Sandbox Code Playgroud)

JsFiddle的例子

如果您想了解更多关于calc(expression)您的信息,请访问网站.


Mat*_*t L 20

当我试图找到这个问题的答案时,这仍然是谷歌的最高结果.我没有必要在我的项目中支持旧浏览器,我觉得我在flex-box中找到了更好,更简单的解决方案.下面的CSS片段就是必要的.

我还展示了如果屏幕高度太小,如何使主要内容可滚动.

html,
body {
  height: 100%;
}
body {
  display: flex;
  flex-direction: column;
}
header {
  min-height: 60px;
}
main {
  flex-grow: 1;
  overflow: auto;
}
footer {
  min-height: 30px;
}
Run Code Online (Sandbox Code Playgroud)
<body style="margin: 0px; font-family: Helvetica; font-size: 18px;">
  <header style="background-color: lightsteelblue; padding: 2px;">Hello</header>
  <main style="overflow: auto; background-color: lightgrey; padding: 2px;">
    <article style="height: 400px;">
      Goodbye
    </article>
  </main>
  <footer style="background-color: lightsteelblue; padding: 2px;">I don't know why you say, "Goodbye"; I say, "Hello."</footer>
</body>
Run Code Online (Sandbox Code Playgroud)

  • 这是未来的方法.无需知道页眉/页脚的确切高度.现在可以达到百分比. (5认同)
  • 目前大多数浏览器支持flex.我想我会选择这个解决方案.由于响应性,这似乎是最好的解决方案 (2认同)

Eri*_*nke 13

这种新的现代方法是通过从视口的垂直高度减去页眉和页脚的高度来计算垂直高度.

//CSS
header { 
  height: 50px;
}
footer { 
  height: 50px;
}
#content { 
  height: calc(100vh - 50px - 50px);
}
Run Code Online (Sandbox Code Playgroud)