JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.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>Picture Perfect 2</title>
<script>
// Picture perfect constructor
function PicturePerfect(img,options){
var self = this;
options = options || {};
self.options = options;
self.img = img;
self.img.className = self.img.className += " picture-perfect";
self.initialized = !(options.lazy != false && self.lazyLoad);
self.maxWindowSize = window.innerWidth;
self._calculateSizes = function(){
if(options.calculateSize != false && self.setElementSize){
self.setElementSize(img);
}
}
self._updateSources = function(){
if(options.dynamicSources != false && self.updateSources){
self.updateSources(self.img);
}
}
self._mimicBackgroundImage = function(){
if(options.mimicBackgroundImage != false && self.mimicBackgroundImage){
self.mimicBackgroundImage(self.img);
}
}
// ON VIEWPORT PROXIMITY
self.onProximity = function(){
self.initialized = true;
self.img.className = self.img.className += " picture-perfect-ready";
self.img.addEventListener("load",self.onLoad);
window.addEventListener("resize",function(){
setTimeout(self.onResize,100);
});
self._calculateSizes();
self._updateSources();
}
self.onResize = function(){
if(self.maxWindowSize < window.innerWidth){
self.maxWindowSize = window.innerWidth;
self._updateSources();
}
self._calculateSizes();
self._mimicBackgroundImage();
}
self.onLoad = function(ev){
self._mimicBackgroundImage();
}
self.initialized ? self.onProximity() : self.lazyLoad();
self._mimicBackgroundImage();
}
// WRAPPER FOR EXECUTING JUST IN TIME INITIALIZATION
var JIT_IMG =...
CSS
[mimic-background-image-container]{
position: relative !important;
overflow: hidden !important;
}
[mimic-background-image-container] > *{
position: relative;
z-index: 2;
}
[mimic-background-image-wrapper]{
z-index: 1;
position: absolute;
overflow: hidden;
top:0;
left: 0;
bottom:0;
right:0;
background-position: center;
background-size: cover;
width: 100%;
height: 100%;
}
[mimic-background-image-wrapper] img{
position: absolute;
max-width: initial !important;
max-height: initial !important;
width: 100%;
height: auto;
top:0;
left:0;
overflow-x: hidden;
}
.cover{
background-size: cover;
}
.contain{
background-size: contain;
}
img {
width: 100%;
}
.element-with-background{
width: 100%;
height: 50vh;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
[mimic-background-image-container]{
border : 2px dotted #000;
}