欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

固定网页页脚的最佳方法(译)_html/css_WEB-ITnose

程序员文章站 2022-06-08 18:10:13
...
原文地址:http://tutorialzine.com/2016/03/quick-tip-the-best-way-to-make-sticky-footers/

在开发网页布局的时候,你可能已经遇到了这个问题:

你可能会设置一个页脚在 body 的最后一部分,但是当页面中没有太多内容的时候,页脚就会留在屏幕的中间,它的下面会出现很大面积的空白。

在这个小教程中,我们将使用现代化的技术来构建一个页脚,保证页脚在任何时候都固定在页面的底部。

为了防止上述情况的发生,我们将使用 Flexbox 来建立我们的网页,它是 CSS3 所提供的建立响应式布局的方法。对于那些你不熟悉的 Flexbox 的模型和它的属性,我会留下一些链接在文章的结尾。

我们使用的例子很简单,头部、主要部分、页脚。下面是 HTML,没有什么特别的部分。

    
...
...
...

为了使用 Flex,我们将 body 的 display 属性设置为 flex,然后将 flex-direction 设置为 column(默认是 horizontal),另外设置 html 和 body 的高度为 100%,填充整个屏幕。

html{    height: 100%;} body{    display: flex;    flex-direction: column;    height: 100%;} 

现在我们将设置下面的这几个 flex 属性,网页中每个部分占用的空间。

  • flex-grow:元素在一个容器中对可分配空间占用的比率。
  • flex-shrink:如果空间不足,元素收缩的比率。
  • flex-basis:元素的默认值。

我们希望页眉和页脚占用固定的一部分空间,剩下的空间全都分成主要内容。这样的布局 CSS 如下:

header{  /* We want the header to have a static height,   it will always take up just as much space as it needs.  */  /* 0 flex-grow, 0 flex-shrink, auto flex-basis */  flex: 0 0 auto;} .main-content{  /* By setting flex-grow to 1, the main content will take up   all of the remaining space on the page.   The other elements have flex-grow: 0 and won't contest the free space. */  /* 1 flex-grow, 0 flex-shrink, auto flex-basis */  flex: 1 0 auto;} footer{  /* Like the header, the footer will have a static height - it shouldn't grow or shrink.  */  /* 0 flex-grow, 0 flex-shrink, auto flex-basis */  flex: 0 0 auto;} 

你可以点击下面的图片查看我们的演示的页面,点击粉色的达按钮,你可以改变网页的内容量,你将观察到无论什么时候页脚都是在网页的底部。

结论

正如你所看到的,Flexbox 在布局中是一个强有力的工具。几乎所有的主流浏览器都支持它,IE 浏览器需要在版本在 IE9+。

这里有一些学习 Flexbox 的经验:

  • CSS 技巧之 Flexbox。 here
  • 专门使用 Flexbox 技术的网站。 here
  • 5分钟的互动课程。 here