1. 程式人生 > >移動web圖片高度自適應的解決方案

移動web圖片高度自適應的解決方案

display 頁面布局 網頁 頁面 osi 完成 defined 取值 ott

由於圖片的加載是在dom加載完成之後進行的,於是,在手機端瀏覽網頁時,經常會看到頁面剛打開時很多內容疊在一起,當圖片加載完成後,頁面會由於圖片加載完成出現明顯的抖動
技術分享圖片

針對這個問題,有以下幾種解決方案


  • 媒體查詢+px

  • rem

  • vm

  • padding

媒體查詢+px


@media screen and(max - width: 320 px) {
    img {
        height: 50px;
    }
}

移動端設備種類繁多,媒體查詢固然精準,但相應的是工作量的增加

rem

rem這個低調的單位隨著webapp的興起,儼然成為了手機端屏幕適配的最佳方案


img {
    height: 0.5rem;
}

但由於rem的小數像素問題,可能會導致1px偏差的產生,就看你是不是處女座了

vm

相對於視口的寬度或高度中較小的那個,其中最小的那個被均分為100單位的vm
算是比較完美的一個解決方案了,不過ios8以下及android4.4以下不支持

padding

padding是可以百分比取值的,詳見padding-properties(https://www.w3.org/TR/CSS2/box.html#padding-properties)

The percentage is calculated with respect to the width of the generated box‘s containing block, even for ‘padding-top‘ and ‘padding-bottom‘. If the containing block‘s width depends on this element, then the resulting layout is undefined in CSS 2.1.

即取值為百分比時,計算出來的padding邊距是相對於其父元素的寬度計算的(margin類同),如下圖:
技術分享圖片

那麽,解決圖片占位的問題就很簡單了。
頁面布局如下:


<style>
    * {
        margin: 0;
        padding: 0;
    }
    ul {
        overflow: hidden;
    }
    li {
        width: 50%;
        float: left;
        text-align: center;
    }
    img {
        width: 100%
    }
</style>
<ul>
    <li>
        <div class="cover">
            <img src="2222.png" >
        </div>
        <div>
            文字
        </div>
    </li>
</ul>

這裏使用偽元素替代div充當子元素,由於padding-top使圖片距離cover頂部100%,用相對定位到頂端。


.cover {
    position: relative;
    font-size: 0;
    display: inline-block;
    width: 100%
}
.cover img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
}
.cover:after {
    content: ‘\20‘;
    padding-top: 100%;
    display: block;
}

頁面最終效果如下:
技術分享圖片

上述例子只適用於圖片寬高1:1的情況,對於其他比例的圖片需要修改padding-top值,例如寬高2:1的圖片,padding-top改為50%即可

原文地址:https://mp.weixin.qq.com/s/C0SG4m_nDWfClwdof_Ohmw

移動web圖片高度自適應的解決方案