我在 CSS 网格布局中找到了用于粘性页脚的 CodePen 解决方案,但它对我来说有两个问题:
- 它有点丑
min-height: 100%
和height: 100%
- 它仅适用于正文中的两个元素(一个 div 和一个页脚)
我需要一些适用于这种 HTML 结构的东西:
<body>
<nav>Some navigation buttons</nav>
<main>The content</main>
<footer>Copyrights and stuff</footer>
</body>
我真的不想将 <nav>
和 <main>
成 <div>
,我很乐意在纯 CSS 中这样做。
// Not required!
// This is just to demo functionality.
$("#add").on("click", function() {
$("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo(".content");
});
html {
height: 100%;
}
body {
min-height: 100%;
display: grid;
grid-template-rows: 1fr auto;
}
.content {
padding: 20px;
}
.footer {
grid-row-start: 2;
grid-row-end: 3;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font: 16px Sans-Serif;
}
h1 {
margin: 0 0 20px 0;
}
p {
margin: 0 0 20px 0;
}
.footer {
background: #42A5F5;
color: white;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<h1>Sticky Footer with Grid</h1>
<p><button id="add">Add Content</button></p>
</div>
<footer class="footer">
Footer
</footer>
原文由 Mitiko 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是一个 CSS Grid 解决方案,但为目标使用一个类要好得多。
使用网格区域这将非常简单: