1.為什么使用flex布局伙单?
傳統(tǒng)的布局基于盒模型商源,需要使用 float ,display 屬性牡彻,并且還要精確計(jì)算寬度及外邊距,會(huì)很麻煩缎除;
而 Flex 布局总寻,可以簡(jiǎn)便、完整渐行、響應(yīng)式地實(shí)現(xiàn)各種頁(yè)面布局,自動(dòng)精確控制對(duì)齊肴沫,無(wú)需計(jì)算蕴忆。
1.png
傳統(tǒng)布局代碼實(shí)現(xiàn)以上效果:
li {
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
background-color: pink;
/*浮動(dòng)并需要計(jì)算*/
float: left;
margin-right: 192px;
}
flex布局代碼實(shí)現(xiàn)以上效果:
ul {
display: flex;
justify-content: space-between;
}
li {
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
background-color: pink;
}
2. 實(shí)現(xiàn) flex 布局的步驟
(1)指定一個(gè)盒子為伸縮盒子
.box{
display: -webkit-flex; /* 兼容Webkit 內(nèi)核的瀏覽器 */
display: flex;
}
(2)設(shè)置屬性來(lái)調(diào)整此盒的子元素的布局方式
3. 給伸縮盒子添加的屬性
(1) flex-direction屬性:決定主軸的方向
(主軸:Flex容器的主軸主要用來(lái)配置Flex項(xiàng)目; 側(cè)軸:與主軸垂直的軸稱(chēng)作側(cè)軸)
.box {
flex-direction: row | row-reverse | column | column-reverse;
}
flex-direction屬性.png
(2) flex-wrap屬性:在一行上排不下全部的項(xiàng)目時(shí)套鹅,決定換行方式
.box{
flex-wrap: nowrap | wrap | wrap-reverse;
}
flex-wrap屬性.png
(3) flex-flow屬性是flex-direction屬性和flex-wrap屬性的簡(jiǎn)寫(xiě)形式卓鹿,默認(rèn)值為row nowrap。
(4) justify-content屬性定義了項(xiàng)目在主軸上的對(duì)齊方式减牺。
.box {
justify-content: flex-start | flex-end | center | space-between | space-around;
}
justify-content屬性.png
(5) align-items屬性定義項(xiàng)目在交叉軸上如何對(duì)齊拔疚。
.box {
align-items: flex-start | flex-end | center | baseline | stretch;
}
align-items屬性.png
(6) align-content屬性堆棧排列,可對(duì)應(yīng)用flex-wrap: wrap后產(chǎn)生的換行進(jìn)行控制
.box {
align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}
align-content屬性.png
4. 給子元素添加的屬性
(1) order 屬性 控制子元素的順序栋艳,數(shù)值越小句各,排列越靠前,默認(rèn)為0凿宾。
.first {
order: 20;
}
.second {
order: 25;
}
.third {
order: 21;
}
order屬性.png
(2) flex 屬性 控制子元素伸縮比例初厚,分配父元素剩余的空間
.first {
flex: 1;
}
.second {
flex: 2;
}
.third {
flex: 1;
}
.fourth {
width: 600px;
}
flex屬性.png
(3) align-self 屬性 允許單個(gè)項(xiàng)目有與其他項(xiàng)目不一樣的對(duì)齊方式,可覆蓋align-items屬性排作。默認(rèn)值為auto亚情,表示繼承父元素的align-items屬性妄痪,如果沒(méi)有父元素,則等同于stretch贩疙。
.item {
align-self: auto | flex-start | flex-end | center | baseline | stretch;
}
例子:
.box {
align-items: center;
}
.box .third {
align-self: flex-start;
}
align-self 屬性.png