移動端padding和margin的百分比設定實現佔位
阿新 • • 發佈:2018-12-15
資源請求和載入都是需要時間的。對於圖片一些內容的展示,當圖片沒有加載出來時。容器高為零,那麼下面的dom元素會上移。當圖片載入後,會容器撐開。這樣會造成頁面的重排。
為了解決以上問題我們可以使用padding的百分比佔位實現(或者margin)。
讓我們把padding這是為百分比時。他百分比對應的是父級的寬的比(W3C規定)
我們就實現了佔位。我們需要佔位的空間新增內容,這時我們就需要定位屬性或者浮動來解決(當父級高度設定為0的時候有驚喜)
* { margin: 0; padding: 0; list-style: none; } .wrapper { /* 彈性盒子。換行處理。內容居中 */ display: flex; flex-wrap: wrap; justify-content: center; } .box { position: relative; width: 25%; padding-bottom: 25%; background-color: #eee; float: left; /* background-color: green; */ margin-left: 10px; margin-bottom: 10px; } .box img{ position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
CSS基本樣式,我們可以用定時器模擬圖片的載入過程。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; list-style: none; } .wrapper { /* 彈性盒子。換行處理。內容居中 */ display: flex; flex-wrap: wrap; justify-content: center; } .box { position: relative; width: 25%; padding-bottom: 25%; background-color: #eee; float: left; /* background-color: green; */ margin-left: 10px; margin-bottom: 10px; } .box img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } </style> </head> <body> <div class="wrapper"> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> </div> <script> let box = document.getElementsByClassName('box'); let imgArr = [0, 1, 2, 3, 4, 5, 6, 7, 8]; let index = 0; let timer = setInterval(() => { let img = `<img src="./images/${index}.jpg" />` box[index].innerHTML = img; index++; if (index == imgArr.length) { clearInterval(timer) } }, 1000) </script> </body> </html>
文章有點老~不過利於理解