在常见的盒模型中,当要控制元素(div)的排列表现方式(无论是水平还是垂直)时,一般会使用 position、float、或 display 等属性来实现,这些属性虽然使用比较常见,但是对于特殊的排列布局方式的实现却并不简洁。
flex(弹性布局)是一种新的布局方案,使用简洁灵活,目前所有主流浏览器已支持,是新项目的首选布局方案。本文尝试利用 felx 实现常见的页脚置底布局。
flex 父容器属性
为一个普通的容器加上 display: flex;
,它便成了一个 flex 父容器(此处称之为 box)。
.box {
display: flex; /* or inline-flex */
}
flex 父容器可选 4 个轴方向,分别是:
row
(默认值):水平从左到右row-reverse
:水平从右到左column
:垂直从上到下column-reverse
:垂直从下到上
.box {
flex-direction: row | row-reverse | column | column-reverse;
}
父容器 box 除了 flex-direction 属性外,还有 flex-wrap、flex-flow、justify-content、align-items、align-content 等。
flex 子项目属性
父容器 box 内的元素就是子项目 item,子容器有 order、flex-grow、flex-shrink、flex-basis、flex、align-self 等属性。这里我们需要理解下 flex-grow、flex-shrink、flex-basis 这 3 个属性。
1、flex-grow
flex-grow 属性定义子项目的增长能力,默认为 0 不增长,设为 1 时子项目将增长至充满所有剩余空间。
2、fles-shrink
flex-shrink 属性定义子项目的收缩能力,默认为 0 不收缩,设为 1 时子项目将在空间不足时自动收缩。
3、flex-basis
flex-basis 属性定义子项目的默认大小,子项目占据空间大小就是根据 flex-basis 属性来计算的,由此得到父容器剩余空间大小,之后再考虑分配。flex-basis 默认值为 auto,在这种情况下项目的宽度由 width 值决定。若不为 auto,则项目宽度由 flex-basis 的值决定,此时忽略 width 值。
4、flex
flex 属性是 flex-grow、flex-shrink、flex-basis 的集合,默认值为 0 1 auto,即等价于 flex-grow: 0; flex-shrink: 1; flex-basis: auto;
。
页脚恒置底
现在回到我们的主题,我们的需求是在正文内容过少时页脚仍然能够留在浏览器视野的底部,而不是往上浮,导致页脚下方出现空白。
flex 布局的解决方法是,将 body 设置为 flex 容器,然后调整 body 容器下 header、content、footer 子项目占用空间的策略,我们希望 header 和 footer 只占用预设置的高度,content 能够自动增长并占据所有剩余空间。根据前面的分析,header 和 footer 不需要有自动增长和收缩能力,通过 flex-grow: 0; flex-shrink: 0;flex-basis: auto;
的设置来达到目的,即 flex: 0 0 auto;
。 content 需要有自动增长能力,即 flex-grow: 1;
,其他维持默认,即 flex: 1 0 auto;
1、html
<html>
<body>
<header>I am Header</header>
<main class="content">I am content</main>
<footer>I am Footer</footer>
</body>
</html>
2、css style
html{
height: 100%;
}
body{
display: flex;
flex-direction: column;
height: 100%;
}
header{
flex: 0 0 auto;
}
.main-content{
flex: 1 0 auto;
}
footer{
flex: 0 0 auto;
}
参考资料