彈性盒模型之flex屬性
這一章節學習flex彈性盒子模型,根據下面的例子來理解一下:
實現上圖效果,我們需要輸入以下代碼:
<style> /*給父級元素的display屬性設置爲fle即可*/ .box{ height:400px; background:skyblue; display:flex; } .box1{ width:200px; height:200px; background:red; } .box2{ width:200px; height:200px; background:red; } .box3{ width:200px; height:200px; background:green; } </style>
<body> <div class="box"> <div class="box1"></div> <div class="box2"></div> <div class="box3"></div> </div> </body>
上面的代碼:
三個塊元素設置大小以及背景色,在父容器中添加flex。
技術點的解釋:
1、設置display: flex屬性可以把塊級元素在一排顯示。
2、flex需要添加在父元素上,改變子元素的排列順序。
3、默認爲從左往右依次排列,且和父元素左邊沒有間隙。
14-2 使用justify-content屬性設置橫軸排列方式
justify-content屬性,本屬性定義了項目在主軸上的對齊方式。結合上一節的布局例子進行理解,屬性值分別爲:
justify-content: flex-start | flex-end | center | space-between | space-around;
flex-start:交叉軸的起點對齊
.box { background: blue; display: flex; justify-content: flex-start; }
flex-end:右對齊
.box{ background: blue; display: flex; justify-content: flex-end; }
center: 居中
.box { background: blue; display: flex; justify-content: center; }
space-between:兩耑對齊,項目之間的間隔都相等。
.box { background: blue; display: flex; justify-content: space-between; }
space-around:每個項目兩側的間隔相等。所以,項目之間的間隔比項目與邊框的間隔大一倍。
.box { background: blue; display: flex; justify-content: space-around; }
14-3 使用align-items屬性設置縱軸排列方式
align-items屬性,本屬性定義了項目在交叉軸上的對齊方式。屬性值分別爲:
align-items: flex-start | flex-end | center | baseline | stretch;
結合右側編輯器中的布局以及下面的樣式設置進行理解:
flex-start:默認值,左對齊
.box { height: 700px; background: blue; display: flex; align-items: flex-start; }
flex-end:交叉軸的終點對齊
.box { height: 700px; background: blue; display: flex; align-items: flex-end; }
center:交叉軸的中點對齊
.box { height: 700px; background: blue; display: flex; align-items: center; }
baseline:項目的第一行文字的基線對齊。
.box { height: 700px; background: blue; display: flex; align-items: baseline; }
三個盒子中設置不同的字體大小,可以參考右側編輯器中的代碼進行測試。
stretch(默認值):如果項目未設置高度或設爲auto,將佔滿整個容器的高度。
.box { height: 300px; background: blue; display: flex; align-items: stretch; } .box div { /*不設置高度,元素在垂直方向上鋪滿父容器*/ width: 200px; }
14-4 給子元素設置flex佔比
flex屬性,設置子元素相對於父元素的佔比。
可以參考右側編輯器的代碼,測試效果如下:
技術點的解釋:
1、給子元素設置flex屬性,可以設置子元素相對於父元素的佔比。
2、flex屬性的值只能是正整數,表示佔比多少。
3、給子元素設置了flex之後,其寬度屬性會失效。