使用css grid实现粘性页脚的核心做法是将页面主体容器设为grid布局,并定义两行:第一行为`1fr`(占据剩余空间),第二行为`auto`(由页脚内容决定高度)。这样当内容不足时,页脚自动贴底;内容溢出时,页脚随内容向下滚动。

如何设置HTML结构以配合Grid布局
需要确保根元素或主容器应用`display: grid`,并将子元素按顺序排列。通常将`

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Sticky Footer with CSS Grid</title>
<style>
html, body {
height: 100%;
margin: 0;
}
.container {
display: grid;
grid-template-rows: 1fr auto;
min-height: 100vh;
}
main {
padding: 20px;
background-color: #f0f0f0;
}
footer {
background-color: #333;
color: white;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<main>
<p>这里是主要内容区域。如果内容很少,页脚会贴在底部。</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p>
</main>
<footer>
<p>这是粘性页脚</p>
</footer>
</div>
</body>
</html>预期结果:在浏览器中打开上述代码,无论`
htmlq 是一个命令行工具,使用 CSS 选择器从 HTML 中提取内容,相当于 jq 的 HTML 版本。该工具使用 Rust 编写,允许你通过 CSS 选择器将 HTML 管道化,直接从终端提取文本、属性和结构化内容。
如何处理内容超出视口高度的情况
当`

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Sticky Footer with Overflow</title>
<style>
html, body {
height: 100%;
margin: 0;
}
.container {
display: grid;
grid-template-rows: 1fr auto;
min-height: 100vh;
}
main {
padding: 20px;
background-color: #f0f0f0;
}
/* 添加大量内容以测试溢出 */
.long-content {
height: 1500px;
background-color: #e0e0e0;
margin-bottom: 20px;
}
footer {
background-color: #333;
color: white;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<main>
<div class="long-content"></div>
<p>更多内容...</p>
</main>
<footer>
<p>这是粘性页脚</p>
</footer>
</div>
</body>
</html>预期结果:当`
基于grid-template-rows属性值的具体问题
如果将`grid-template-rows`的第一行值改为`auto`而不是`1fr`,页脚将不再具有粘性效果,而是紧跟在内容之后,即使内容很少,页脚也不会贴底。这是因为`auto`不会强制占据剩余空间。

















