网页布局是CSS的一个重点应用,布局的传统方案布局的传统解决方案,基于盒状模型,依赖 display
属性 + position
属性 + float
属性。它对于那些特殊布局非常不方便,比如,垂直居中就不容易实现。
2009年,W3C 提出了一种新的方案----Flex 布局,可以简便、完整、响应式地实现各种页面布局。目前,它已经得到了所有浏览器的支持,这意味着,现在就能很安全地使用这项功能。

一、Flex(Flexible Box)布局是什么
Flex是弹性布局
任何一个容器都可以指定为 Flex 布局。
.box{
display: flex;
}
行内元素也可以使用 Flex 布局。
.box{
display: inline-flex;
}
Webkit 内核的浏览器,必须加上-webkit前缀。
.box{
display: -webkit-flex; /* Safari */
display: flex;
}
二、容器属性
1、flex-direction
决定主轴的方向(即项目的排列方向)
row(默认值):主轴为水平方向,起点在左端。
row-reverse:主轴为水平方向,起点在右端。
column:主轴为垂直方向,起点在上沿。
column-reverse:主轴为垂直方向,起点在下沿。
.box {
display: flex;
flex-direction:row;
}

.box {
display: flex;
flex-direction:row-reverse;
}

.box {
display: flex;
flex-direction:column;
}

.box {
display: flex;
flex-direction:column-reverse;
}

2、flex-wrap
默认情况下,项目都排在一条线(又称"轴线")上。flex-wrap属性定义,如果一条轴线排不下,如何换行。
nowrap(默认):不换行。
wrap:换行,第一行在上方。
wrap-reverse:换行,第一行在下方。
.box {
display: flex;
flex-wrap:nowrap;
}

.box {
display: flex;
flex-wrap:wrap;
}

.box {
display: flex;
flex-wrap:wrap-reverse;
}

3、flex-flow
flex-flow属性是flex-direction属性和flex-wrap属性的简写形式,默认值为row nowrap。
.box {
flex-flow: <flex-direction> || <flex-wrap>;
}
4、justify-content属性
justify-content属性定义了项目在主轴上的对齐方式。
flex-start(默认值):左对齐
flex-end:右对齐
center: 居中
space-between:两端对齐,项目之间的间隔都相等。
space-around:每个项目两侧的间隔相等。所以,项目之间的间隔比项目与边框的间隔大一倍。
.box {
display: flex;
justify-content:flex-start;
}

.box {
display: flex;
justify-content:flex-end;
}

.box {
display: flex;
justify-content:center;
}

.box {
display: flex;
justify-content:space-between;
}

.box {
display: flex;
justify-content:space-around;
}

5、align-items
align-items属性定义项目在交叉轴上如何对齐。
flex-start:交叉轴的起点对齐。
flex-end:交叉轴的终点对齐。
center:交叉轴的中点对齐。
baseline: 项目的第一行文字的基线对齐。
stretch(默认值):如果项目未设置高度或设为auto,将占满整个容器的高度。
.box {
display: flex;
align-items:flex-start;
}

.box {
display: flex;
align-items:flex-end;
}

.box {
display: flex;
align-items:stretch;
}

.box {
display: flex;
align-items:baseline;
}

.box {
display: flex;
align-items:center;
}

6、align-content
align-content属性定义了多根轴线的对齐方式。如果项目只有一根轴线,该属性不起作用。
flex-start:与交叉轴的起点对齐。
flex-end:与交叉轴的终点对齐。
center:与交叉轴的中点对齐。
space-between:与交叉轴两端对齐,轴线之间的间隔平均分布。
space-around:每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍。
stretch(默认值):轴线占满整个交叉轴。
.box {
display: flex;
flex-wrap: wrap;
align-content:stretch;
}

.box {
display: flex;
flex-wrap: wrap;
align-content:center;
}

.box {
display: flex;
flex-wrap: wrap;
align-content:flex-start;
}

.box {
display: flex;
flex-wrap: wrap;
align-content:flex-end;
}

.box {
display: flex;
flex-wrap: wrap;
align-content:space-between;
}

.box {
display: flex;
flex-wrap: wrap;
align-content:space-around;
}

未完待续......
网友评论