如何在不使用固定位置的情况下滚动时将页脚保持在页面的底部

300 阅读2分钟

一个粘性的页脚 总是显示在浏览器窗口的底部。但有时我们没有足够的内容来降低页脚。在这种情况下,内容就会挂在窗口的中间。

在本教程中,我将向你展示如何在不使用绝对位置的情况下将页脚保持在页面的底部。

如何在页面底部创建一个粘性页脚?

早些时候,我们通过将<body> 的高度设为100%,并将包装器最小高度设为100%,来制作一个固定的页脚。

之后,将页脚设置为position: absolute; ,同时将底部值设置为0。这将 在页面底部创建一个 粘性页脚。

如今。 flexbox已被所有浏览器广泛支持。通过使用 弹性我们可以很容易地在页面的底部创建一个页脚区域。让我们先检查一下HTML结构。

HTML布局

<body>
	<div class="wrapper">
		<div class="header">Site Logo</div>
		<div class="content"> 
			Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
		</div>
		<div class="footer">All Right Reserved</div>
	</div>
</body>
  • <body>.wrapper ,包裹了标题内容页脚部分。
  • .header 部分将显示在页面的顶部。
  • .content 将容纳所有的页面内容。
  • 这个.footer 部分将显示在页面的底部。

应用CSS

body {
	padding: 0;
	margin: 0;
	color: #5f5f5f;
}
.wrapper {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
}

.header {
	border-bottom: 1px solid #dad8d8;
	background-color: #fff;
	padding: 0 20px;
	padding-top: 1em;
	padding-bottom: 1em;
	font-size: 30px;
}

.content {
	background-color: #f7f7f7;
	flex-grow: 1;
	padding: 20px;
	font-size: 24px;
	line-height: 34px;
}

.footer {
	border-top: 1px solid #dad8d8;
	background-color: #fff;
	padding: 0 20px;
	padding-top: 1em;
	padding-bottom: 1em;
	font-size: 20px;
	text-align: center;
}

让我们直接讨论主要话题,而不讨论其他不相关的样式:

  • 我们已经将.wrapper 显示风格设置为 灵活并将flex-direction 设置为 以使所有章节都垂直显示。
  • 这里我们也设置了min-height: 100vh; 。这意味着.wrapper 项目的最小高度总是与整个视口高度相同。
  • .content ,我们设置了flex-grow: 1; 。根据MDN,flex-grow有助于分配flex容器中的剩余空间。因此,.content 部分将覆盖剩余的空间。

总结

我想这个方法会帮助你解决页面底部的页脚问题。今天的教程就到此为止。如果你有任何问题,请在下面留言。