我想建立一个网站,其中有一个固定的标题、一个可变的内容和一个在页面未完全填充时位于底部的页脚。我将使用 CSS Grid Layout为此。
当高度已知时扩展内容元素很容易:
div {
border-width: 1px;
border-style: solid;
}
#container {
width: 200px;
height: 200px;
display: grid;
grid-template-rows: auto 1fr auto;
}
<div id="container">
<div>hello </div>
<div>world</div>
<div>three</div>
</div>
然后我尝试在全窗口浏览器上重现它,我不知道如何告诉应用程序“如果没有足够的内容,高度就是浏览器的大小,否则就是内容”。我认为 min-height: 100%;
应用于 body
会很好 - 但事实并非如此:
body {
display: grid;
grid-template-rows: auto 1fr auto;
grid-template-columns: 1fr auto;
min-height: 100%;
}
.navbar {
grid-row-start: 1;
grid-row-end: 2;
grid-column-start: 1;
grid-column-end: 3;
}
.main {
grid-row-start: 2;
grid-row-end: 3;
grid-column-start: 1;
grid-column-end: 2;
}
.toc {
grid-row-start: 2;
grid-row-end: 3;
grid-column-start: 2;
grid-column-end: 3;
}
.footer {
grid-row-start: 3;
grid-row-end: 4;
grid-column-start: 1;
grid-column-end: 3;
}
此代码创建了正确的网格,但 body
的大小不是浏览器的整个高度:
最佳答案
使用 min-height: 100vh
代替 min-height:100%
。
百分比高度很棘手,因为它们通常需要在父元素 ( full explanation) 上定义高度。
来自规范:
5.1.2. Viewport-percentage lengths: the
vw
,vh
,vmin
,vmax
unitsThe viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
- vw unit - Equal to 1% of the width of the initial containing block.
- vh unit - Equal to 1% of the height of the initial containing block.
- vmin unit - Equal to the smaller of
vw
orvh
.- vmax unit - Equal to the larger of
vw
orvh
.
关于html - 部分填充时如何强制 body 成为屏幕的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45436103/