Skip to main content

Footer

  • 如果页面内容不足够长时, 页脚固定在浏览器窗口的底部.
  • 如果内容足够长时, 页脚固定在页面的最底部.

Negative Margin

Negative bottom margin content-wrapper with fixed height footer:

<body>
<main class="wrapper">
content
<div class="push"></div>
</main>
<footer class="footer"></footer>
</body>

<style>
html,
body {
height: 100%;
margin: 0;
}

.wrapper {
min-height: 100%;

/* Equal to height of footer */

/* But also accounting for potential margin-bottom of last child */
margin-bottom: -50px;
}

.footer,
.push {
height: 50px;
}
</style>

Negative top margin on fixed height footer:

<body>
<main class="content">
<section class="content-inside">content</section>
</main>
<footer class="footer"></footer>
</body>

<style>
html,
body {
height: 100%;
margin: 0;
}

.content {
min-height: 100%;
}

.content-inside {
padding: 20px;
padding-bottom: 50px;
}

.footer {
height: 50px;
margin-top: -50px;
}
</style>

Calculation

calc on fixed height footer:

<body>
<main class="content">content</main>
<footer class="footer"></footer>
</body>

<style>
.content {
min-height: calc(100vh - 70px);
}

.footer {
height: 50px;
}
</style>

Flexbox

Use flex on body:

<body>
<main class="content">content</main>
<footer class="footer"></footer>
</body>

<style>
html,
body {
height: 100%;
}

body {
display: flex;
flex-direction: column;
min-height: 100vh;
}

.content {
flex: 1 0 auto;
}

.footer {
flex-shrink: 0;
}
</style>

Grid

Use grid on body:

<body>
<main class="content">content</main>
<footer class="footer"></footer>
</body>

<style>
html {
height: 100%;
}

body {
display: grid;
grid-template-rows: 1fr auto;
min-height: 100%;
}

.footer {
grid-row: 2 / 3;
}
</style>

Use gird with min-content:

<body>
<div class="grid">
<header>
<!-- ... -->
</header>
<main>
<!-- ... -->
</main>
<footer>
<!-- ... -->
</footer>
</div>
</body>

<style>
.grid {
display: grid;
grid-template-rows: min-content auto min-content;
height: 100vh;
}
</style>