写个布局,当页面高度不够时,底部固定在下面,反之不固定

<!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; on body: 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; and flex-direction: column; on body: This sets up a flexbox layout for the body, arranging its children (main and footer) in a column.
  • flex: 1; on main: This allows the main 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:

  1. Short Content: When the content within main is short and doesn't fill the viewport, min-height: 100vh on the body ensures the body still takes up the full viewport height. The flex: 1 on main allows it to expand to fill the remaining space, pushing the footer to the bottom.

  2. Long Content: When the content within main is long enough to exceed the viewport height, the flex: 1 on main allows it to expand vertically. The body 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.

posted @   王铁柱6  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示