实现 CSS Sticky Footer 布局,可以通过以下步骤实现:
第一步:创建 HTML 结构
先创建一些基本的 HTML 标记以容纳页面内容。一般情况下,我们需要包含一个固定头部(Header)、主体内容(Main)和一个底部(Footer)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sticky Footer Layout</title>
</head>
<body>
<header>
<!-- Header content -->
</header>
<main>
<!-- Main content -->
</main>
<footer>
<!-- Footer content -->
</footer>
</footer>
</html>
第二步:添加样式
一旦我们有了一些基本的 HTML 结构,便可使用 CSS 将其布局。为 Sticky Footer 布局选择 CSS 伪元素技术是一种不错的方法。通过使用 CSS 伪元素 :before
和 :after
,我们可以实现一个自适应的 Footer 部分,即使不存在高度。当页面内容小于屏幕高度时,Footer 将视图下推到底部。
html, body {
margin: 0;
padding: 0;
height: 100%;
}
body {
display: flex;
flex-direction: column;
}
main {
flex: 1;
}
footer:after {
content: "";
display: block;
height: 50px;
}
footer {
height: 50px;
}
在上述 CSS 中,我们使用 flexbox
布局使 main
自适应页面内容。然后,我们使用 :before
伪元素在 header
下部分设置一个空白元素;我们使用 :after
伪元素在 footer
下方设置一个空白元素。
请注意:在 footer:after
块中间,设置了一个 display: block
属性以占据一定高度,并将 footer
的高度设置为相同的高度,保持视觉上的一致。
示例一:基本的 Sticky Footer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sticky Footer Layout</title>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
}
body {
display: flex;
flex-direction: column;
}
main {
flex: 1;
}
footer:after {
content: "";
display: block;
height: 50px;
}
footer {
height: 50px;
}
</style>
</head>
<body>
<header>
<h1>Header</h1>
</header>
<main>
<p>This is the main content</p>
</main>
<footer>
<p>This is the footer</p>
</footer>
</footer>
</html>
示例二:使用 Flexbox 和 Grid 布局的 Sticky Footer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sticky Footer Layout</title>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
}
#container {
display: grid;
grid-template-rows: auto 1fr auto;
height: 100%;
}
header {
grid-row: 1 / 2;
background: #3B5998;
color: white;
padding: 10px;
}
main {
grid-row: 2 / 3;
padding: 10px;
margin-bottom: 50px;
}
footer {
grid-row: 3 / 4;
height: 50px;
background: #3B5998;
color: white;
padding: 10px;
}
</style>
</head>
<body>
<div id="container">
<header>
<h1>Header</h1>
</header>
<main>
<p>This is the main content</p>
</main>
<footer>
<p>This is the footer</p>
</footer>
</div>
</body>
</html>
在这个示例中,我们使用了 grid
布局,加强了 Sticky Footer 布局的弹性。注意到,在 grid-template-rows
属性中,我们使用了 auto
, 1fr
和 auto
来定义三部分样式。其中,1fr
表示 main
元素应该占据剩余的可用空间。边距问题同样在这个示例中得到处理。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:css sticky footer经典布局的实现 - Python技术站