DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
CSS3 伸縮盒實戰:display: box 與 box-flex 的用法與 Firefox 相容性陷阱
編輯:HTML5詳解     

前陣子做手機端專案,第一次把 CSS3 的伸縮盒(flexbox)寫法正式用在正式環境裡。那個時候瀏覽器對這套屬性的支援還很零散,幾乎每個屬性都得補上各家前綴才能跑。下面把完整寫法,還有實際踩到的相容性坑,一次整理出來。

一、頁面結構

先用兩組 s-indLine 容器,每組裡放兩個導航方塊,每個方塊由一個圖示 span 和一段文字組成:

<div class="s-indLine">
    <div class="s-indNav s-indIntro">
        <span class="s-icon"></span>
        <p>品牌介紹</p>
    </div>
    <div class="s-indNav s-indInfo">
        <span class="s-icon"></span>
        <p>優惠信息</p>
    </div>
</div>

<div class="s-indLine">
    <div class="s-indNav s-indShop">
        <span class="s-icon"></span>
        <p>門店查找</p>
    </div>
    <div class="s-indNav s-indGoods">
        <span class="s-icon"></span>
        <p>熱賣商品</p>
    </div>
</div>

二、樣式撰寫

關鍵在父容器上宣告 display: box 並把方向設為水平,子元素則靠 box-flex 來平均分掉剩餘空間:

.s-indLine{
    display: -webkit-box;
    display: -moz-box;
    display: box;
    margin-bottom: 10px;
    -moz-box-orient: horizontal;
    -webkit-box-orient: horizontal;
    box-orient: horizontal;
}

.s-indLine .s-indNav{
    -webkit-box-flex: 5;
    -moz-box-flex: 5;
    box-flex: 5;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    border-radius: 10px;
    color: #ffffff;
    text-align: center;
    height: 105px;
    padding: 15px 0px;
    font-size: 1.5rem;
}

.s-indLine .s-indNav:first-child{
    margin-right: 10px;
}

.s-indIntro{ background: #4eb566; }
.s-indInfo{  background: #ffa422; }
.s-indShop{  background: #7788f2; }
.s-indGoods{ background: #ef604d; }

.s-indLine .s-indNav .s-icon{
    width: 50px;
    height: 50px;
    display: inline-block;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-position: center;
}

.s-indIntro .s-icon{ background-image: url("group.png"); }
.s-indInfo .s-icon{  background-image: url("group.png"); }
.s-indShop .s-icon{  background-image: url("group.png"); }
.s-indGoods .s-icon{ background-image: url("group.png"); }

補充一點:子元素並不是非寫 box-flex 不可,直接給 width 也能達到同樣效果,margin 和 padding 也都能照常設定。最後做出來的效果如下:

三、Firefox 上的兩個相容性問題

在 Chrome 或手機端以 -webkit 為核心的瀏覽器上除錯,上面的程式碼完全正常;但一換到 Firefox 就變形了,如下圖:

這個問題的解法很樸素:必須幫父元素補上明確寬度,例如 width: 100%;,Firefox 才會正確計算伸縮。

另一個差異更讓人頭痛。前面說「子元素可以不設 box-flex,改用 width」,這條規則在 Firefox 上並不成立——它不會理會子元素的 width,你必須老老實實寫 box-flex。所以在需要跨瀏覽器的專案裡,box-flex 反而是比較保險的選擇。

寫這類帶前綴的屬性時,建議養成兩個習慣:一是把標準寫法放在最後或最前便於日後移除前綴,二是不同核心各自寫一份對照表,除錯時會省下大量時間。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved