2017-07-10 141 views
1

我目前有以下CSS代碼,我將其應用於顯示響應圖像的div元素。使用CSS顯示加載圖片

.my-img-container { 
 
    position: relative; 
 
    &:before { 
 
    display: block; 
 
    content: " "; 
 
    background: url("https://lorempixel.com/300/160/") no-repeat; 
 
    background-size: 100% 100%; 
 
    width: 100% !important; 
 
    padding-top: 56.25%; 
 
    } 
 
    >img { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    width: 100% !important; 
 
    height: 100% !important; 
 
    } 
 
}
<div class="my-img-container"> 
 
    <img srcset="https://lorempixel.com/540/304 540w, https://lorempixel.com/960/540 960w" sizes="(min-width: 576px) 540px, 100vw" src="https://lorempixel.com/300/160"> 
 
</div>

我試圖做的是有背景的圖像顯示,同時響應圖像加載,因此在CSS中content,但它不工作。任何想法爲什麼?

回答

2

您可以設置微調的背景圖像:

html, 
 
body { 
 
    height: 100%; 
 
    margin: 0; 
 
} 
 

 
img { 
 
    display: block; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    width: 100%; 
 
    height: 100%; 
 
    background: url(https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif) no-repeat center; 
 
}
<img srcset="https://lorempixel.com/540/304 540w, https://lorempixel.com/960/540 960w" sizes="(min-width: 576px) 540px, 100vw" src="https://lorempixel.com/300/160">

4

不必加載較小的圖像顯示爲裝載機的,只需旋轉僞元素來代替。

它具有啓動速度快於圖像並保存額外服務器調用的好處。

.my-img-container { 
 
    position: relative; 
 
    padding-top: 56.25%; 
 
} 
 
.my-img-container:before { 
 
    content: " "; 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    width: 80px; 
 
    height: 80px; 
 
    border: 2px solid red; 
 
    border-color: transparent red transparent red; 
 
    border-radius: 50%; 
 
    animation: loader 1s linear infinite; 
 
} 
 
.my-img-container > img { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    width: 100% !important; 
 
    height: 100% !important; 
 
} 
 
@keyframes loader { 
 
    0% { 
 
    transform: translate(-50%,-50%) rotate(0deg); 
 
    } 
 
    100% { 
 
    transform: translate(-50%,-50%) rotate(360deg); 
 
    } 
 
}
<div class="my-img-container"> 
 
    <img srcset="https://lorempixel.com/540/304 540w, https://lorempixel.com/960/540 960w" sizes="(min-width: 576px) 540px, 100vw" src="https://lorempixel.com/300/160"> 
 
</div>