flex 布局

1.為什么使用flex布局?

傳統(tǒng)的布局基于盒模型,需要使用 float ,display 屬性,并且還要精確計算寬度及外邊距,會很麻煩;
Flex 布局,可以簡便、完整、響應(yīng)式地實現(xiàn)各種頁面布局,自動精確控制對齊,無需計算。

1.png

傳統(tǒng)布局代碼實現(xiàn)以上效果:

 li {
            width: 200px;
            height: 200px;
            text-align: center;
            line-height: 200px;
            background-color: pink;

            /*浮動并需要計算*/
            float: left;        
            margin-right: 192px;
        }

flex布局代碼實現(xiàn)以上效果:

ul {
            display: flex;
            justify-content: space-between;
        }

li {
            width: 200px;
            height: 200px;
            text-align: center;
            line-height: 200px;
            background-color: pink;
        }

2. 實現(xiàn) flex 布局的步驟

(1)指定一個盒子為伸縮盒子

.box{
  display: -webkit-flex; /* 兼容Webkit 內(nèi)核的瀏覽器 */
  display: flex;
}

(2)設(shè)置屬性來調(diào)整此盒的子元素的布局方式

3. 給伸縮盒子添加的屬性

(1) flex-direction屬性:決定主軸的方向
(主軸:Flex容器的主軸主要用來配置Flex項目; 側(cè)軸:與主軸垂直的軸稱作側(cè)軸)

.box {
  flex-direction: row | row-reverse | column | column-reverse;
}
flex-direction屬性.png

(2) flex-wrap屬性:在一行上排不下全部的項目時,決定換行方式

.box{
  flex-wrap: nowrap | wrap | wrap-reverse;
}
flex-wrap屬性.png

(3) flex-flow屬性是flex-direction屬性和flex-wrap屬性的簡寫形式,默認值為row nowrap。

(4) justify-content屬性定義了項目在主軸上的對齊方式。

.box {
  justify-content: flex-start | flex-end | center | space-between | space-around;
}

justify-content屬性.png

(5) align-items屬性定義項目在交叉軸上如何對齊。

.box {
  align-items: flex-start | flex-end | center | baseline | stretch;
}

align-items屬性.png

(6) align-content屬性堆棧排列,可對應(yīng)用flex-wrap: wrap后產(chǎn)生的換行進行控制


.box {
  align-content: flex-start | flex-end | center | space-between | space-around | stretch;
}
align-content屬性.png

4. 給子元素添加的屬性

(1) order 屬性 控制子元素的順序,數(shù)值越小,排列越靠前,默認為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 屬性 允許單個項目有與其他項目不一樣的對齊方式,可覆蓋align-items屬性。默認值為auto,表示繼承父元素的align-items屬性,如果沒有父元素,則等同于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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容