A CSS image gallery is a sleek and interactive way to showcase multiple images on a webpage. The gallery we’re going to discuss today is designed with responsive layouts, allowing images to rearrange themselves based on the screen size, making it perfect for both desktop and mobile viewing. Let’s dive into the code that makes this possible.
Project Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
<body>
<section class="gallery">
<div>
<article>
<img src="https://images.pexels.com/photos/104842/bmw-vehicle-ride-bike-104842.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="motorbike 1">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>12 Likes</div>
</article>
<article>
<img src="https://images.pexels.com/photos/11567227/pexels-photo-11567227.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load" alt="motorbike 2">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>23 Likes</div>
</article>
<article>
<img src="https://images.pexels.com/photos/4542987/pexels-photo-4542987.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="notorbike 3">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>6 Likes</div>
</article>
</div>
<div>
<article>
<img src="https://images.pexels.com/photos/18233419/pexels-photo-18233419/free-photo-of-a-building-in-a-city.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load" alt="mountains 1">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>22 Likes</div>
</article>
<article>
<img src="https://images.pexels.com/photos/950859/pexels-photo-950859.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="hand">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>18 Likes</div>
</article>
<article>
<img src="https://images.pexels.com/photos/25823790/pexels-photo-25823790/free-photo-of-blocks-of-flats-in-city.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load" alt="beach">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>145 Likes</div>
</article>
</div>
<div>
<article>
<img src="https://images.pexels.com/photos/1659438/pexels-photo-1659438.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" alt="man on rock">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>145 Likes</div>
</article>
<article>
<img src="https://images.pexels.com/photos/27582996/pexels-photo-27582996/free-photo-of-a-statue-of-arco-da-rua-augusto-in-lisbon.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load" alt="trees">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>98 Likes</div>
</article>
<article>
<img src="https://images.pexels.com/photos/27351031/pexels-photo-27351031/free-photo-of-essaouira-view.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load" alt="sky">
<div><span class="material-symbols-outlined material-fill-1">favorite</span>37 Likes</div>
</article>
</div>
</section>
<!-- codelives -->
<script src="index.js"></script>
</body>
</html>
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
min-height: 100svh;
display: grid;
place-content: center;
background: white;
font-family: system-ui,sans-serif;
padding: 2rem;
}
.material-fill-1 {
font-variation-settings:
'FILL'1,
'wght'400,
'GRAD'0,
'opsz'48
}
p{
color: white;
font-size: 0.8rem;
text-align: center;
margin-top: 1rem;
}
a{
color: orange;
}
a:hover{
text-decoration: underline;
}
.gallery {
--_height: 250px;
--_gap: .5rem;
--_grid-rows: var(--_height) var(--_height) var(--_height);
--_height-hover: calc(var(--_height) * 2);
--_height-not-hover: calc(var(--_height) / 2);
width: 100%;
max-width: 800px;
display: grid;
gap: var(--_gap);
}
@media (min-width:720px){
.gallery {
grid-template-columns: repeat(3,1fr);
}
}
.gallery>div {
height: fit-content;
display: grid;
grid-template-rows: var(--_grid-rows);
gap: var(--_gap);
transition: grid-template-rows 300ms ease-in-out;
}
.gallery>div>article {
position: relative;
}
.gallery>div>article>div{
position: absolute;
bottom: 0;
right: 0;
background: #00000070;
font-size: 0.65rem;
color: white;
display: flex;
align-items: center;
gap: .25rem;
padding: .15rem 0.5rem;
}
.gallery>div>article>div>span{
font-size: 0.7rem;
color: red;
}
.gallery img {
width: 100%;
height: 100%;
object-fit: cover;
}
.gallery>div:has(>article:nth-child(1):hover) {
--_grid-rows: var(--_height-hover) var(--_height-not-hover) var(--_height-not-hover);
}
.gallery>div:has(>article:nth-child(2):hover) {
--_grid-rows: var(--_height-not-hover) var(--_height-hover) var(--_height-not-hover);
}
.gallery>div:has(>article:nth-child(3):hover) {
--_grid-rows: var(--_height-not-hover) var(--_height-not-hover) var(--_height-hover);
}
.gallery>div>article:hover {
background-color: rgb(151, 152, 201);
color: #FFF;
}
const marqueeItems = document.querySelectorAll(".marquee-item");
const btnPrev = document.querySelector(".arrow-prev");
const btnNext = document.querySelector(".arrow-next");
const conf = { duration: 1, ease: "power.inOut" };
window.addEventListener("load", function () {
const loop = horizontalLoop(marqueeItems, {
repeat: -1,
paddingRight: 30,
speed: 0.2,
draggable: true
});
marqueeItems.forEach(function (item) {
item.addEventListener("mouseenter", () => loop.pause());
item.addEventListener("mouseleave", () => loop.play());
});
btnPrev.addEventListener("click", () => loop.previous(conf));
btnNext.addEventListener("click", () => loop.next(conf));
});
/*
This helper function makes a group of elements animate along the x-axis in a seamless, responsive loop.
Features:
- Uses xPercent so that even if the widths change (like if the window gets resized), it should still work in most cases.
- When each item animates to the left or right enough, it will loop back to the other side
- Optionally pass in a config object with values like draggable: true, center: true, speed (default: 1, which travels at roughly 100 pixels per second), paused (boolean), repeat, reversed, and paddingRight.
- The returned timeline will have the following methods added to it:
- next() - animates to the next element using a timeline.tweenTo() which it returns. You can pass in a vars object to control duration, easing, etc.
- previous() - animates to the previous element using a timeline.tweenTo() which it returns. You can pass in a vars object to control duration, easing, etc.
- toIndex() - pass in a zero-based index value of the element that it should animate to, and optionally pass in a vars object to control duration, easing, etc. Always goes in the shortest direction
- current() - returns the current index (if an animation is in-progress, it reflects the final index)
- times - an Array of the times on the timeline where each element hits the "starting" spot.
*/
function horizontalLoop(items, config) {
let timeline;
items = gsap.utils.toArray(items);
config = config || {};
gsap.context(() => {
// use a context so that if this is called from within another context or a gsap.matchMedia(), we can perform proper cleanup like the "resize" event handler on the window
let onChange = config.onChange,
lastIndex = 0,
tl = gsap.timeline({
repeat: config.repeat,
onUpdate:
onChange &&
function () {
let i = tl.closestIndex();
if (lastIndex !== i) {
lastIndex = i;
onChange(items[i], i);
}
},
paused: config.paused,
defaults: { ease: "none" },
onReverseComplete: () =>
tl.totalTime(tl.rawTime() + tl.duration() * 100)
}),
length = items.length,
startX = items[0].offsetLeft,
times = [],
widths = [],
spaceBefore = [],
xPercents = [],
curIndex = 0,
indexIsDirty = false,
center = config.center,
pixelsPerSecond = (config.speed || 1) * 100,
snap =
config.snap === false ? (v) => v : gsap.utils.snap(config.snap || 1), // some browsers shift by a pixel to accommodate flex layouts, so for example if width is 20% the first element's width might be 242px, and the next 243px, alternating back and forth. So we snap to 5 percentage points to make things look more natural
timeOffset = 0,
container =
center === true
? items[0].parentNode
: gsap.utils.toArray(center)[0] || items[0].parentNode,
totalWidth,
getTotalWidth = () =>
items[length - 1].offsetLeft +
(xPercents[length - 1] / 100) * widths[length - 1] -
startX +
spaceBefore[0] +
items[length - 1].offsetWidth *
gsap.getProperty(items[length - 1], "scaleX") +
(parseFloat(config.paddingRight) || 0),
populateWidths = () => {
let b1 = container.getBoundingClientRect(),
b2;
items.forEach((el, i) => {
widths[i] = parseFloat(gsap.getProperty(el, "width", "px"));
xPercents[i] = snap(
(parseFloat(gsap.getProperty(el, "x", "px")) / widths[i]) * 100 +
gsap.getProperty(el, "xPercent")
);
b2 = el.getBoundingClientRect();
spaceBefore[i] = b2.left - (i ? b1.right : b1.left);
b1 = b2;
});
gsap.set(items, {
// convert "x" to "xPercent" to make things responsive, and populate the widths/xPercents Arrays to make lookups faster.
xPercent: (i) => xPercents[i]
});
totalWidth = getTotalWidth();
},
timeWrap,
populateOffsets = () => {
timeOffset = center
? (tl.duration() * (container.offsetWidth / 2)) / totalWidth
: 0;
center &&
times.forEach((t, i) => {
times[i] = timeWrap(
tl.labels["label" + i] +
(tl.duration() * widths[i]) / 2 / totalWidth -
timeOffset
);
});
},
getClosest = (values, value, wrap) => {
let i = values.length,
closest = 1e10,
index = 0,
d;
while (i--) {
d = Math.abs(values[i] - value);
if (d > wrap / 2) {
d = wrap - d;
}
if (d < closest) {
closest = d;
index = i;
}
}
return index;
},
populateTimeline = () => {
let i, item, curX, distanceToStart, distanceToLoop;
tl.clear();
for (i = 0; i < length; i++) {
item = items[i];
curX = (xPercents[i] / 100) * widths[i];
distanceToStart = item.offsetLeft + curX - startX + spaceBefore[0];
distanceToLoop =
distanceToStart + widths[i] * gsap.getProperty(item, "scaleX");
tl.to(
item,
{
xPercent: snap(((curX - distanceToLoop) / widths[i]) * 100),
duration: distanceToLoop / pixelsPerSecond
},
0
)
.fromTo(
item,
{
xPercent: snap(
((curX - distanceToLoop + totalWidth) / widths[i]) * 100
)
},
{
xPercent: xPercents[i],
duration:
(curX - distanceToLoop + totalWidth - curX) / pixelsPerSecond,
immediateRender: false
},
distanceToLoop / pixelsPerSecond
)
.add("label" + i, distanceToStart / pixelsPerSecond);
times[i] = distanceToStart / pixelsPerSecond;
}
timeWrap = gsap.utils.wrap(0, tl.duration());
},
refresh = (deep) => {
let progress = tl.progress();
tl.progress(0, true);
populateWidths();
deep && populateTimeline();
populateOffsets();
deep && tl.draggable
? tl.time(times[curIndex], true)
: tl.progress(progress, true);
},
onResize = () => refresh(true),
proxy;
gsap.set(items, { x: 0 });
populateWidths();
populateTimeline();
populateOffsets();
window.addEventListener("resize", onResize);
function toIndex(index, vars) {
vars = vars || {};
Math.abs(index - curIndex) > length / 2 &&
(index += index > curIndex ? -length : length); // always go in the shortest direction
let newIndex = gsap.utils.wrap(0, length, index),
time = times[newIndex];
if (time > tl.time() !== index > curIndex && index !== curIndex) {
// if we're wrapping the timeline's playhead, make the proper adjustments
time += tl.duration() * (index > curIndex ? 1 : -1);
}
if (time < 0 || time > tl.duration()) {
vars.modifiers = { time: timeWrap };
}
curIndex = newIndex;
vars.overwrite = true;
gsap.killTweensOf(proxy);
return vars.duration === 0
? tl.time(timeWrap(time))
: tl.tweenTo(time, vars);
}
tl.toIndex = (index, vars) => toIndex(index, vars);
tl.closestIndex = (setCurrent) => {
let index = getClosest(times, tl.time(), tl.duration());
if (setCurrent) {
curIndex = index;
indexIsDirty = false;
}
return index;
};
tl.current = () => (indexIsDirty ? tl.closestIndex(true) : curIndex);
tl.next = (vars) => toIndex(tl.current() + 1, vars);
tl.previous = (vars) => toIndex(tl.current() - 1, vars);
tl.times = times;
tl.progress(1, true).progress(0, true); // pre-render for performance
if (config.reversed) {
tl.vars.onReverseComplete();
tl.reverse();
}
if (config.draggable && typeof Draggable === "function") {
proxy = document.createElement("div");
let wrap = gsap.utils.wrap(0, 1),
ratio,
startProgress,
draggable,
dragSnap,
lastSnap,
initChangeX,
wasPlaying,
align = () =>
tl.progress(
wrap(startProgress + (draggable.startX - draggable.x) * ratio)
),
syncIndex = () => tl.closestIndex(true);
typeof InertiaPlugin === "undefined" &&
console.warn(
"InertiaPlugin required for momentum-based scrolling and snapping. https://greensock.com/club"
);
draggable = Draggable.create(proxy, {
trigger: items[0].parentNode,
type: "x",
onPressInit() {
let x = this.x;
gsap.killTweensOf(tl);
wasPlaying = !tl.paused();
tl.pause();
startProgress = tl.progress();
refresh();
ratio = 1 / totalWidth;
initChangeX = startProgress / -ratio - x;
gsap.set(proxy, { x: startProgress / -ratio });
},
onDrag: align,
onThrowUpdate: align,
overshootTolerance: 0,
inertia: true,
snap(value) {
//note: if the user presses and releases in the middle of a throw, due to the sudden correction of proxy.x in the onPressInit(), the velocity could be very large, throwing off the snap. So sense that condition and adjust for it. We also need to set overshootTolerance to 0 to prevent the inertia from causing it to shoot past and come back
if (Math.abs(startProgress / -ratio - this.x) < 10) {
return lastSnap + initChangeX;
}
let time = -(value * ratio) * tl.duration(),
wrappedTime = timeWrap(time),
snapTime = times[getClosest(times, wrappedTime, tl.duration())],
dif = snapTime - wrappedTime;
Math.abs(dif) > tl.duration() / 2 &&
(dif += dif < 0 ? tl.duration() : -tl.duration());
lastSnap = (time + dif) / tl.duration() / -ratio;
return lastSnap;
},
onRelease() {
syncIndex();
draggable.isThrowing && (indexIsDirty = true);
},
onThrowComplete: () => {
syncIndex();
wasPlaying && tl.play();
}
})[0];
tl.draggable = draggable;
}
tl.closestIndex(true);
lastIndex = curIndex;
onChange && onChange(items[curIndex], curIndex);
timeline = tl;
return () => window.removeEventListener("resize", onResize); // cleanup
});
return timeline;
}
//made by codelives
Conclusion
This responsive CSS image gallery is a great example of how modern CSS techniques like Grid Layout can be used to create a dynamic and visually appealing web component. By combining clean HTML structure with advanced CSS, you can build galleries that are both functional and aesthetically pleasing.