flexbox(四)伸縮佈局中的margin&伸縮性&主軸對齊方式

伸縮佈局中的margin:

當使用flex屬性計算伸縮項目的寬度的時候,爲auto的margin會值爲0


在主軸(main axis)方向

  • 如剩餘空間爲正數,則剩餘空間會被平均分配在擁有主軸方向auto margin(s)的flex元素之間。
  • 如剩餘空間爲負數,則將主軸方向的auto margin(s)設定爲‘0’。

在側軸(cross axis)方向

  • 如果擁有側軸方向auto margins(s)的元素的outer cross size(計算時將auto margins(s)作‘0’計算)小於其所在的flex line的cross size,則將剩餘空間平均分配給auto margin(s)。
  • 否則,如果側軸方向block-startinline-start方向的margin爲auto,則將其設定爲‘0’。設置相對方向的margin值,使此元素的outer cross size等於其所在的flex line的cross size。

伸縮性



flex-grow 是擴展比率 默認爲0
flex-shrink 是收縮比率 默認爲1
flex-basis 伸縮基準值默認爲auto,意味着伸縮基準值與元素的主軸長度屬性值相同,如果省略該值,則默認爲0.

第一種情況
flex-parent 是父級,而且他的寬度是固定爲800px,不會改變;
開始設置子級flex屬性;
<style type="text/css">
    .flex-son:nth-child(1){
        flex: 3 1 200px;
    }
    .flex-son:nth-child(2){
        flex: 2 2 300px;
    }
    .flex-son:nth-child(3){
        flex: 1 3 500px;
    }
</style>
flex-basis總和加起來爲1000px; 那麼 1000px > 800px (父級的寬度);子元素勢必要壓縮;溢出了200px;

son1 = (flex-shrink) * flex-basis;
son2 = (flex-shrink) * flex-basis;
…..
sonN = (flex-shrink) * flex-basis;

如果flex-basis的總和加起來大於父級寬度,子級被壓縮,最後的選擇是flex-shrink來進行壓縮計算
加權值 = son1 + son2 + …. + sonN;

那麼壓縮後的計算公式就是

壓縮後寬度 w = (子元素flex-basis值 * (flex-shrink)/加權值) * 溢出值

所以最後的加權值是
1*200 + 2*300 + 3*500 = 2300px

son1的擴展量:(200 * 1/ 2300) * 200,即約等於17px;
son2的擴展量:(300 * 2/ 2300) * 200,即約等於52px;
son3的擴展量:(500 * 3/ 2300) * 200,即約等於130px;

最後son1、son2、son3,的實際寬度爲:
200 – 16  = 184px;
300 – 52  = 248px;
500 – 230 = 370px;

第二種情況

上面的例子已經說明,繼續看第二個例子,同樣上面的例子,我們改下父級寬度爲1200px;
flex-basis的總和爲 1000px,小於父級寬度,將有200px的剩餘寬度;
既然有剩餘,我們就不要加權計算,剩餘的寬度將根據flex-grow,值得總和進行百分比,那麼200px就會根據份數比來分配剩餘的空間;

剩餘後寬度 w = (子元素flex-grow值 /所有子元素flex-grow的總和) * 剩餘值

總分數爲 total = 1 + 2 + 3;

son1的擴展量:(3/total) * 200,即約等於100px;
son2的擴展量:(2/total) * 200,即約等於67px;
son3的擴展量:(1/total) * 200,即約等於33px;

最後son1、son2、son3,的實際寬度爲:
200 + 100 = 300px;
300 + 67 = 367px;
500 + 33 = 533px;


主軸對齊方式


The justify-content property aligns flex items along the main axis of the current line of the flex container. This is done after any flexible lengths and any auto margins have been resolved. Typically it helps distribute extra free space leftover when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line.

 

該屬性是控制在伸縮容器中當前行的主軸來對其伸縮項目的對齊方式的,他是在任何的伸縮長度變化和margin爲auto佈局解決完成之後再佈局的。當該行的伸縮項目不變的時候或者自動伸縮變化已經達到最大值的時候 開始分配剩餘空間,當伸縮項目溢出該行的時候,也會施加一些控制。

該屬性的值和上一篇博客中伸縮行側軸對齊一樣,不再贅述。


參考:http://www.heibaipig.com/blog/?p=450



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章