How to make background images slide?

Dani AI

Generated

For : first decide whether you want one image to slide inside its container (a continuous pan) or a sequence of different images (a slideshow). split those two cases; below are modern, practical ways to implement each, plus performance and accessibility tips you can apply now.

If you want a single image to move, prefer animating a positioned element with transform rather than relying on the browser to animate background offsets. That keeps the work on the compositor thread and is much smoother on mobile. Use will-change: transform sparingly, and add a prefers-reduced-motion fallback so the animation can be disabled for users who request reduced motion:

.slide-wrap { position: relative; overflow: hidden; }
.slide-img { position: absolute; left:0; top:0; width:200%; height:100%; background: url(img.jpg) center/cover no-repeat;
             animation: slide 12s linear infinite; will-change: transform; }

@keyframes slide { to { transform: translateX(-50%); } }

@media (prefers-reduced-motion: reduce) { .slide-img { animation: none; } }

For a slideshow of different images, layer images (or use <img> with srcset) and crossfade via opacity. Use CSS animations for simple fades, and use JavaScript with requestAnimationFrame when you need precise control, throttling, or to pause when the tab is hidden. Optimize images (proper size/compression), lazy-load offscreen slides, and test on low-end devices. See requestAnimationFrame and prefers-reduced-motion on MDN for implementation details: requestAnimationFrame and prefers-reduced-motion.

Recommended Answers

All 2 Replies

If you mean that you want to make the background image move, you can use JavaScript to modify the 'backgroundPosition' CSS setting and animate it in a timing loop.

If you mean that you want to make the background image like a slideshow, you can use JavaScript to change the 'backgroundImage' CSS setting in a timing loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.