只需将连续元素的高度设置为等于 100% 并将内容 DIV 设置为在 Y 轴上滚动:
<header>
<h1>Sandwich Layout</h1>
</header>
<div id="main" role="main">
</div>
<footer>
Footer stuff here
</footer>
html,
body { height: 100%; margin: 0; padding: 0; } /* This is important */
header,
footer { background: #ccc; height:20%; }
#main { height: 60%; overflow-y:scroll; }
小提琴:http: //jsfiddle.net/kboucher/3E8Gg/
2020 年更新:
HTML:
<header>
<h1>Sandwich Layout</h1>
</header>
<div class="main" role="main">
<div class="fake-height">Content here</div>
</div>
<footer>
Footer stuff here
</footer>
CSS:
body,
html {
height: 100vh;
overflow: hidden;
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
}
header,
footer {
background: #eee;
padding: 1rem;
}
.main {
flex: 1 0 auto;
height: 0; // prevents flex box expanding out of view-height
overflow-y: auto;
padding: 1rem;
.fake-height {
height: 1000px;
}
}
https://codepen.io/kboucher/pen/dyomxWN