写个布局,当页面高度不够时,底部固定在下面,反之不固定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sticky Footer</title>
<style>
body {
display: flex;
flex-direction: column;
min-height: 100vh; /* Ensure the body takes up at least the full viewport height */
margin: 0;
}
main {
flex: 1; /* Allow the main content to grow and shrink */
padding: 20px;
}
footer {
background-color: #f0f0f0;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<main>
<h1>Page Content</h1>
<p>Add enough content here to make the page scrollable. When the content is short, the footer should stick to the bottom. When there's a lot of content, the footer should follow naturally.</p>
<p>More content...</p>
<p>Even more content...</p>
</main>
<footer>
<p>This is the footer.</p>
</footer>
</body>
</html>
Explanation:
min-height: 100vh;
onbody
: This ensures the body element always takes up at least the full viewport height. This is crucial for the sticky footer to work correctly.display: flex;
andflex-direction: column;
onbody
: This sets up a flexbox layout for the body, arranging its children (main and footer) in a column.flex: 1;
onmain
: This allows themain
element to expand and take up all available space between the top and the footer. This is what pushes the footer down when the content is long.
How it works:
-
Short Content: When the content within
main
is short and doesn't fill the viewport,min-height: 100vh
on thebody
ensures the body still takes up the full viewport height. Theflex: 1
onmain
allows it to expand to fill the remaining space, pushing the footer to the bottom. -
Long Content: When the content within
main
is long enough to exceed the viewport height, theflex: 1
onmain
allows it to expand vertically. Thebody
grows beyond the viewport height due to the content, and the footer naturally follows the content.
This approach is clean, uses only CSS, and avoids unnecessary JavaScript or complicated HTML structures. It's widely supported by modern browsers. You can easily customize the styling of the main
and footer
elements to fit your design.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)