Learn with us how to create an Image switcher in CSS!
If you found us on TikTok on the following post, check out this article and copy-paste the full code!
Happy coding! 😻
@creative.tim Check out tutorial #48 for the full code 👀 link in bio #webdevelopment #techtok #csscoding #programming #programmingexercises ♬ original sound - Creative Tim
1. HTML Code
- let n = 14;
- let p = n*n;
- let img1 = "https://picsum.photos/id/29/4000/2670";
- let img2 = "https://picsum.photos/id/15/2500/1667";
style
- for(let x = 0; x < n; x++)
| .grid:has(.cell[style*="--i: #{x}"]:hover) { --ki: #{x} }
| .grid:has(.cell[style*="--j: #{x}"]:hover) { --kj: #{x} }
input(type="checkbox")(id="image")
label.grid(style=`--n: ${n};--img1: url(${img1});--img2: url(${img2})`)(for="image")
- for(let j = 0; j < n; j++)
- for(let i = 0; i < n; i++)
.cell(style=`--i: ${i};--j: ${j};`)
2. CSS Code
.grid {
--size: 80vmin;
display: grid;
width: var(--size);
aspect-ratio: 1;
grid-template-columns: repeat(var(--n), 1fr);
cursor: pointer;
}
.cell {
--abs-i: max(var(--ki,0) - var(--i),var(--i) - var(--ki,0));
--abs-j: max(var(--kj,0) - var(--j),var(--j) - var(--kj,0));
--rel-i: calc(var(--abs-i)/var(--n));
--rel-j: calc(var(--abs-j)/var(--n));
--sum: calc(var(--rel-i)*var(--rel-i) + var(--rel-j)*var(--rel-j));
--sqr: var(--sum);
display: grid;
transform-style: preserve-3d;
animation: m1 .4s calc(var(--sqr)*.6s) both;
}
.cell:before,
.cell:after {
content: "";
grid-area: 1/1;
background: var(--img1)
calc(var(--i)/var(--n)*100%) calc(var(--j)/var(--n)*100%)/var(--size) var(--size);
backface-visibility: hidden;
}
.cell:after {
background-image: var(--img2);
transform: rotateY(180deg);
}
input:checked + label .cell {
animation-name: m2;
}
@keyframes m1 {
0% {transform: perspective(300px) scale(1.05) rotateY(0deg)}
to {transform: perspective(300px) scale(1.05) rotateY(180deg)}
}
@keyframes m2 {
0% {transform: perspective(300px) scale(1.05) rotateY(180deg)}
to {transform: perspective(300px) scale(1.05) rotateY(0deg)}
}
@supports (z-index: sqrt(4)) {
.cell {
--sqr: sqrt(var(--sum));
}
}
body {
margin: 0;
min-height: 100vh;
display: grid;
place-content: center;
background: #4B4E6D;
}
input {
display: none;
}
I hope you did find this tutorial useful!
For more web development or UI/UX design tutorials, follow us on:
Other useful resources: