我正在努力从使用表格进行布局,再到使用div(是的,是的辩论)。我有3个div,标题,内容和页脚。页眉和页脚各50px。如何让页脚div保持在页面底部,内容div填充两者之间的空间?我不想硬编码内容div高度,因为屏幕分辨率可能会改变。

有帮助吗?

解决方案

Flexbox解决方案

使用flex布局我们可以实现这一点,同时允许自然高度页眉和页脚。页眉和页脚都将分别粘贴到视口的顶部和底部(非常像本机移动应用程序),主内容区域将填充剩余空间,而任何垂直溢出都将在该区域内滚动。

查看JS小提琴

<强> HTML

<body>
  <header>
    ...
  </header>
  <main>
    ...
  </main>
  <footer>
    ...
  </footer>
</body>  

<强> CSS

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

body {
  display: flex;
  flex-direction: column;
}

header,
footer {
  flex: none;
}

main {
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  flex: auto;
}

其他提示

总结(这来自 CSS Sticky Footer 链接由Traingamer提供),这就是我使用的:

html, body 
{ 
    height: 100%; 
} 

#divHeader
{
    height: 100px;
}

#divContent
{
    min-height: 100%; 
    height: auto !important; /*Cause footer to stick to bottom in IE 6*/
    height: 100%; 
    margin: 0 auto -100px; /*Allow for footer height*/
    vertical-align:bottom;
}

#divFooter, #divPush
{
    height: 100px; /*Push must be same height as Footer */
}

<div id="divContent">
    <div id="divHeader">
        Header
    </div>

    Content Text

    <div id="divPush"></div>
</div>
<div id="divFooter">
    Footer
</div>

要扩展Mitchel Sellers的答案,请将您的内容div高度:100%并给它一个自动余量。

有关完整说明和示例,请参阅Ryan Fait的 CSS粘滞页脚

由于您知道标题的大小(高度),请将其放在内容div中(或使用边距)。

如果您的内容比窗口更大(更高),绝对位置会给您带来问题。

使用CSS Grid执行此操作的方法:

<强>的index.html

<html>
  <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link href="main.css" rel="stylesheet">
  </head>
  <body>
    <main>
      <header>Header</header>
      <section>Content</section>
      <footer>Footer</footer>
    </main>
  </body>
</html>

<强>的main.css

body {
    margin: 0;
}
main {
    height: 100%;
    display: grid;
    grid-template-rows: 100px auto 100px;
}
section {
    height: 100%;
}

如果您尝试最大化内容div的高度,请在CSS添加

身高:100%;

#footer {
 clear: both;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top