CSS Image Swap on Hover
A shop thumbnail that crossfades to a second product photo on hover, like most online stores do.
<a class="img-swap" href="#">
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' fill='%23e0e7ff'/%3E%3Crect x='12' y='14' width='16' height='18' rx='2' fill='%236366f1'/%3E%3Cpath d='M16 15v-3a4 4 0 0 1 8 0v3' fill='none' stroke='%234338ca' stroke-width='1.6'/%3E%3C/svg%3E" alt="Canvas tote bag, front" width="200" height="200">
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' fill='%23fde68a'/%3E%3Ccircle cx='20' cy='14' r='5' fill='%23b45309'/%3E%3Cpath d='M12 40c0-10 3-16 8-16s8 6 8 16z' fill='%2392400e'/%3E%3Crect x='22' y='26' width='11' height='12' rx='1.5' fill='%236366f1'/%3E%3Cpath d='M25 27v-2a2.5 2.5 0 0 1 5 0v2' fill='none' stroke='%234338ca' stroke-width='1.2'/%3E%3C/svg%3E" alt="" width="200" height="200">
</a>
.img-swap {
display: grid;
width: 200px;
overflow: hidden;
border-radius: 14px;
}
.img-swap img {
grid-area: 1 / 1;
display: block;
width: 100%;
height: auto;
transition: opacity 0.4s ease, transform 0.6s ease;
}
.img-swap img + img {
opacity: 0;
}
.img-swap:hover img + img,
.img-swap:focus-visible img + img {
opacity: 1;
transform: scale(1.04);
}
.img-swap:focus-visible {
outline: 3px solid #1c1917;
outline-offset: 3px;
}
@media (prefers-reduced-motion: reduce) {
.img-swap img {
transition: none;
}
}
About this CSS Image Swap on Hover
This CSS Image Swap on Hover is 35 lines of pure CSS (0.5 KB) with no JavaScript and no dependencies. It uses transitions, transforms, CSS Grid and keyboard focus styles. It works in current versions of Chrome, Edge, Safari and Firefox. It works in any stack: plain HTML, React, Vue, Svelte, Astro, WordPress or Webflow.
CSS features used
Customize it
The colors in this snippet. Search and replace them to match your brand:
#1c1917
How to use this image swap on hover
- Copy the HTML and paste it where you want the element to appear.
- Copy the CSS into your stylesheet, or inside a
<style>tag. - Keep the
.img-swapclass name, or rename it in both places. Then tweak colors, sizes and timing to match your design. - Using React or Next.js? Change
classtoclassNamein the HTML. The CSS works as is, including in Tailwind projects (put it in your global stylesheet).
Building with an AI tool?
“Copy for AI” copies a short prompt for Cursor, Claude Code, Lovable, Bolt or v0. Your AI tool opens the Markdown version of this snippet and reads the HTML, CSS and setup notes there. If your tool can't open links, with the code instead. More ways to use copy CSS with AI.