JSFiddle - React, Tailwind, and code Playground
by kodjoe mambi
HTML
<div class="overlay"></div>
<style id="dynamicCss"></style>
CSS
.overlay {
position: relative;
display: inline-block;
margin-top: 20px;
background: url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6eaeec90e00222e7f62_optimized_990), url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6fb04d71200247e15fb_optimized_990), url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6feec730a0022b756d4_optimized_990), url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6ed7e627d0022f7acad_optimized_990), url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6f020ea4d00234326ee_optimized_990), url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6f7271d190023cb958e_optimized_990), url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b702271d190023cb95b6_optimized_990), url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6f4eab9f000229958a9_optimized_990), url(https://res2.yourwebsite.life/res/5eaf48a4da467d0022126577/6166b6e6fe83f10024675e66_optimized_990);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: 0px 0px, 0px 2796px, 0px 5592px, 0px 8388px, 0px 11184px, 0px 13980px, 0px 16776px, 0px 19572px, 0px 22368px;
animation: 10s scroll infinite alternate linear;
max-width: 50%;
max-height: 90%;
width: 648px;
height: 450px;
border: 3px solid #000;
}
@-webkit-keyframes scroll{
100%{
background-position: 0px -2796px;
}
}
@-moz-keyframes scroll{
100%{
background-position: 0px -2796px;
}
}
@-o-keyframes scroll{
100%{
background-position: 0px -2796px;
}
}
@-ms-keyframes scroll{
100%{
background-position: 0px -2796px;
}
}
@keyframes scroll{
100%{
background-position: 0px -2796px;
}
}
JavaScript
function attachBackgroundHandler() {
const overlay = document.querySelector('.overlay');
const keyframeCssContainer = document.querySelector('#dynamicCss');
const heightRatio = 1312 / 990; // image original height / image original width
const backgroundImageCount = 9;
function calculateBackgroundPositions() {
const overlayWidth = overlay.clientWidth;
const height = overlayWidth * heightRatio;
const totalAnimationHeight = height * (backgroundImageCount - 1);
const backgroundPositionValues = [];
const backgroundAnimationPositions = [];
for (let p = 0; p < backgroundImageCount; p++) {
const position = height * p;
backgroundPositionValues.push(`0px ${position}px`);
backgroundAnimationPositions.push(`0px ${-totalAnimationHeight + position}px`);
}
overlay.style.backgroundPosition = backgroundPositionValues.join();
keyframeCssContainer.textContent = `
@keyframes scroll {
100% {
background-position: ${backgroundAnimationPositions.join()};
}
}
`
};
calculateBackgroundPositions();
window.addEventListener('resize', calculateBackgroundPositions);
}
attachBackgroundHandler();