将div扩展到页面底部(仅限HTML和CSS)

时间:2014-04-08 10:16:39

标签: html css position

这是一个非常简单的问题,但我似乎无法在线找到合适的解决方案。我希望在自然流中有一个元素列表,最后一个元素扩展到页面底部。所以,如果我有

<div id="top" style="height:50px;"></div>
<div id="bottom" style="background:lightgrey;"></div>

我需要元素bottomtop的底部扩展到页面底部。任何只使用html和css的解决方案都是受欢迎的,你可以添加容器div或任何东西,只要我可以动态调整bottom div的大小

编辑: 我不想对bottom的任何值进行硬编码,因为如果bottom调整大小,我希望调整top

这里是满足您所有需求的小提琴:http://jsfiddle.net/8QnLA/

2 个答案:

答案 0 :(得分:52)

解决方案:#1:css表:

html, body {
  height: 100%;
  width: 100%;
}
body {
  display: table;
  margin: 0;
}
#top, #bottom {
  width: 100%;
  background: yellow;
  display: table-row;
}
#top {
  height: 50px;
}
#bottom {
  background: lightgrey;
  height: 100%;
}

html, body {
  height: 100%;
  width: 100%;
}
body {
  display: table;
  margin: 0;
}
#top, #bottom {
  width: 100%;
  background: yellow;
  display: table-row;
}
#top {
  height: 50px;
}
#bottom {
  background: lightgrey;
  height: 100%;
}
<div id="top" style="height:50px;"><span>A header</span></div>
<div id="bottom" style="background:lightgrey;"><span>The content area - extends to the bottom of the page</span></div>

Codepen #1 (little content)

<强> Codepen #2 (lots of content)

解决方案#2:使用计算和视口单元

#top {
  height: 50px;
  background: yellow;
}
#bottom {
  background: lightgrey;
  min-height: calc(100vh - 50px);
}

body {
  margin: 0;
}
#top {
  height: 50px;
  background: yellow;
}
#bottom {
  background: lightgrey;
  min-height: calc(100vh - 50px);
}

Where `min-height: calc(100vh - 50px);` means:

'Let the height of the content div be **at least** 100% of the viewport height minus the 50px height of the header.'
<div id="top" style="height:50px;"><span>A header</span></div>
<div id="bottom" style="background:lightgrey;"><span>The content area - extends to the bottom of the page</span></div>

<强> Codepen #1 (little content)

<强> Codepen #2 (lots of content)

解决方案#3 - Flexbox

body {
  margin: 0;
  min-height: 100vh;
}
body {
  display: flex;
  flex-direction: column;
}
#top {
  height: 50px;
  background: yellow;
}
#bottom {
  background: lightgrey;
  flex: 1;
}

body {
  margin: 0;
  min-height: 100vh;
}
body {
  display: flex;
  flex-direction: column;
}
#top {
  height: 50px;
  background: yellow;
}
#bottom {
  background: lightgrey;
  flex: 1;
}
<div id="top" style="height:50px;"><span>A header</span></div>
<div id="bottom" style="background:lightgrey;"><span>The content area - extends to the bottom of the page</span></div>

<强> Codepen #1 - little content

<强> Codepen #2 - lots of content

答案 1 :(得分:3)

html, body的高度设置为100%。然后,您可以将最后<div>的高度设置为100%,它将与窗口一样高。由于您可能不想滚动,因此您也可以在overflow: hidden上设置html, body

http://jsfiddle.net/GKbzx/