Skip to content

如何让页脚固定在底部? #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jiangshanmeta opened this issue Jul 1, 2017 · 0 comments
Open

如何让页脚固定在底部? #6

jiangshanmeta opened this issue Jul 1, 2017 · 0 comments
Labels

Comments

@jiangshanmeta
Copy link
Owner

在一个网页中通常会有页脚的设置。如果页面内容较少,看起来页脚就像是浮了起来,在浏览器的下面还有一块白色,显得非常难看。我不会告诉你我最近看到的新鲜的页面里还有这种问题,都是同行,给人个面子,不给链接了。那么如何解决这一问题呢?

javascript方案

不难,请自行实现。然而我总是想能用css解决的绝对不用js。先约定一下页面结构:

<body>
	<header id="header">

	</header >
	<main id="header">

	</main>
	<footer id="footer">

	</footer>
</body>

公共的样式设置:

*{
	margin:0;
	padding:0;
}

table方案

这里所说的table并不是说html table,而是css table。在css的display属性中,有一堆关于table的值,比如table,table-row,table-cell。这些值可以帮助我们像表格一样布局而不使用html table。这里用到的是tabletable-row两个值。

我们可以把整个body视为一个table,然后header、main、footer三部分视为table-row。并且让main占据100%高度。可能你觉得很奇怪如果main高度设为100%,那么header和footer的高度岂不是零了?但是table有许多神奇的特性,header和footer会正常显示。这里的header和footer的高度会变成恰能放下内容的高度,main占据剩余空间。因为table的话无论是宽度还是高度计算都比较复杂,web开发者所设置的width或者height都是参考值。

这样你会发现依然没有实现固定在底部。因为body的高度现在是由内容决定的,我们要设置body的最小高度设为视口高度。可以采用100vh这么一个方案,如果担心兼容性问题,可以把高度设为百分比。

代码如下:

body{
	display:table;
	width:100%;
	min-height:100vh;
}
#main{
	display:table-row;
	height:100%;
}

在线demo:固定在底部的页脚——table方案

flex方案

flex作为布局神器,基本上你想到的用flex都能做。这里所需要的是两个属性flex-directionflex-grow。我们需要把body作为 flex盒子,并把flex盒子方向设为column,把我们的主体内容的扩展属性设为1,header和footer不扩展,这样就会让主体内容自动填充空余部分。

代码如下:

body{
	display:flex;
	flex-direction:column;
	min-height:100vh;
}
#main{
	flex-grow:1;
}

在线demo:固定在底部的页脚——flex方案

总结

关于如何实现固定在底部的页脚,其实也有许多方案,但是有各种各样的问题,比如footer的高度必须是固定的。我上面所说的两种纯CSS方案都不需要固定footer的高度,基本上可以直接拿到生产环境里用。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant