flex布局具备便捷、灵活的特色,熟练的运用flex布局能解决大部分布局问题,这里对一些经常使用布局场景作一些总结。css
web页面布局(topbar + main + footbar)
示例代码
要实现的效果以下:html

html代码:web
<div class="container"> <header>header...</header> <main>内容</main> <footer>footer...</footer> </div>
css代码:bash
header{
height:100px;
background:#ccc; } footer{ height:100px; background:#ccc; } .container{ display:flex; flex-direction:column; height:100vh; } main{ flex-grow:1; }
应用的flex属性
本例中主要应用了如下flex属性:ide
- flex-direction:column 使总体布局从上到下排列
- flex-grow:1, 应用于main,使得main自动填充剩余空间
本例中应用以较少的css代码实现了传统的上中下页面布局,其中的关键经过flex-grow的使用避免了当main内容过少时footer部分会被提高到页面上方的问题(传统方式上可能须要靠绝对定位来解决了~)布局
每行的项目数固定并自动换行的列表项
要实现的效果以下:post

html代码:flex
示例代码
css代码:spa
ul{
display:flex;
flex-wrap:wrap;
}
li{
list-style:none;
flex:0 0 25%;
background:#ddd; height:100px; border:1px solid red; }
应用的flex属性
本例中主要应用了如下flex属性:code
-
flex:0 0 25%,至关于flex-basis:25%,使得每个列表项的宽度占外层容器(本例中的ul元素)的25%,所以每行最多可以排开四个列表项。
-
flex-wrap:wrap,使得每行填满时会自动换行
实现自动划分多余空间的列表项
本例的效果和上例中的图2很类似,只是每行为3个固定宽度的列表项,而且各列表项之间留有相同宽度的空隙

传统方式上实现这种效果,不可避免的要用到负margin,那么如今来看了用flex实现的方式吧
示例代码
css代码:
ul{
display:flex;
flex-wrap:wrap;
justify-content:space-between;
border:1px solid black;
}
li{
list-style:none;
width:120px;
background:#ddd; height:100px; border:1px solid red; }
应用的flex属性
本例中主要应用了如下flex属性:
- justify-content:space-between;使主轴方向的多余空间平均分配在两两item之间
平均分配空间的栅格布局
各大UI里栅格布局基本是必备的布局之一,平均分配布局又是栅格布局里最经常使用的布局,利用flex实现平均分配的栅格布局,关键之处就是利用它的自动收缩空间。

示例
html以下:
<div class="row"> <div class="column">column1</div> <div class="column">colum22</div> <div class="column">colum322</div> </div>
css以下:
.row{
display:flex;
flex-wrap:wrap;
border:1px solid black;
}
.column{
list-style:none;
background:#ddd; flex:1; height:100px; border:1px solid red; }
应用的flex属性
本例中主要应用了如下flex属性:
- flex:1 这里针对item应用了flex:1,至关于flex:1 1 0%,而之因此无论各个column元素内容的宽度为多大,都能均分到相等的空间,正式由于至关于在设置了flex-grow:1使得剩余空间按相等比例自动分配的同时又设置了flex-basis:0%,才使得整个空间都平均分配了。
圣杯布局
传统的圣杯布局须要涉及绝对定位、浮动、负margin等几大最头疼属性,有了flex布局之后发现,原来这么简单的配方,也能实现这么复杂的效果哈~

示例代码
html代码:
<div class="container"> <main>main</main> <aside>aside</aside> <nav>nav</nav> </div>
css代码:
.container{
display:flex;
height:100vh;
}
aside{
width:50px;
background:#ccc; } main{ flex-grow:1; background:#def; } nav{ width:80px; background:#ccc; order:-1; }
应用的flex属性
- 对main用flex-grow:1,使得中间主元素空间自动扩充
- 对nav应用order:-1,使得order处于最左侧(html中main写在了最前,以利于优先加载主内容区)
元素水平垂直居中
如何让一个元素同时水平垂直居中?答案不少样也很复杂,可是在这么多样化得答案中flex绝对是最简单的一种了~

示例代码
html代码:
<div class="container"> <div class="inner">我是中间的内容</div> </div>
css代码:
.container{ height:300px; width:300px; border:1px solid red; display:flex; justify-content:center; align-items:center; } .inner{ border:1px solid black; }
应用的flex属性
- justify-content:center;使item元素水平居中
- align-items:center;使item元素垂直居中
这么多场景都难不倒flex有木有,果真名不虚传~( 想更详细的了解flex相关属性的话,请戳flex入门—了解这些flex属性~)