写个布局,当页面高度不够时,底部固定在下面,反之不固定
<!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.