FlexBox彈性盒子計算規則

和FlexBox彈性盒子計算規則相關的屬性有:javascript

  1. margincss

  2. flex-basishtml

  3. flex-growjava

  4. flex-shrinkflex

margin

Flex容器每一行的寬度 = 每一個子容器的寬度 + 子容器margin-left和margin-right的值code

html:
    
    <div class='container'>
        <div class='item first' style='background-color:coral;'></div>
        <div class='item second' style='background-color:lightblue;'></div>
        <div class='item third' style='background-color:khaki;'></div>
    </div>
    
    css:
    
    .container {
            display: flex;
            width: 400px;
        }
        .item {
            height: 40px;
        }
        .first {
            flex: 1 0 0;
            background-color: red;
        }
        .second {
            flex: 2 0 0;
            background-color: blue;
            margin: 0 50px;
        }
        .third {
            flex: 3 0 0;
            background-color: yellow;
        }

總width(400px) = 總margin(100px) + 每一個item的寬度;htm

因爲flex-basis屬性值爲0,剩餘空間爲400px,則各個子盒子會根據自身的flex-grow屬性值及所佔總比重來分配剩餘空間
.first寬度: 400*(1/(1+2+3))
.second寬度: 400*(2/(1+2+3))
.third寬度: 400*(3/(1+2+3))ip

flex-basis

子盒子的基準值it

  • 能夠代替申明width屬性class

  • 同時聲明width屬性和flex-basis屬性時,會以flex-basis的值來計算

  • flex-basis屬性值爲0,在width有申明的狀況下以width來計,width沒有的申明的話,則按其內容來計。

flex-grow

  • flex-grow申明的值爲0,不出現伸展的狀況

  • flex-grow申明的值不爲0,且子盒子的flex-basis(或width)值之和 < 容器的padding的左邊界到右邊界的值。那麼子盒子會根據申明的flex-grow值去分配剩餘的空間。

分配規則是按子盒子flex-grow屬性值所佔百分比來分配: demo見上

flex-shrink

<div class='container'>
    <div class='item first' style="background-color:coral;"></div>
    <div class='item second' style="background-color:lightblue;"></div>
    <div class='item third' style="background-color:khaki;"></div>
</div>

.container {
    display: flex;
    width: 200px;
    height: 400px;
    border: 1px solid #c3c3c3;
}
.first {
    flex-basis: 40px;
    flex-shrink: 1;
}        
.third {
    flex-basis: 40px;
    flex-shrink: 2;
}
.second {
    flex-shrink: 3;
    width: 200px;
}

首先依據flex-basis屬性計算各個彈性盒子的寬度值,(200+40+40)px,一共溢出了80px
而後依據各個彈性盒子的flex-shrink屬性值,算出其加權後的綜合值:
1*40 + 2*40 + 3*200 = 720(px);
.first須要縮小的值:(40\*1/720)*80 約等於4px
.second須要縮小的值:(40\*2/720)*80 約等於9px
.third須要縮小的值:(200\*3/720)*80 約等於67px
第一個盒子的寬度40-4 = 36px
第二個盒子的寬度40-9 = 31px
第三個盒子的寬度200-67 = 133px

  • 若是flex-basis的屬性未設置,即flex-basis: 0,那麼彈性盒子計算多餘空間或者溢出空間的寬度是依據其width的值,若是width未設置,那麼是其內容的寬度

  • 若是同時設置了flex-basis的屬性值和width的值,那麼將會忽略width的值

  • flex-basis可設爲百分比,是相對於祖先申明爲display:flex的元素而言

幾個常見的flex取值:

  • flex: 1; -->> flex: 1 1 0%;

  • flex: none; -->> flex: 0 0 auto;

  • flex: auto; -->> flex: 1 1 auto;

  • flex: 0 auto;或者 flex: initial -->> flex: 0 1 auto; 即爲flex的初始值

相關文章
相關標籤/搜索