Latteforever Devlogs
Sep 05, 2022

Let's design Image Carousel



High-level design:


Implememting layout

A simple version to achieve the layout is to use display:flex to make the images render in a horizontal row and and overflow:hidden to hide images except for one. And programatically change the horizontal scroll offset to show the various images.

There are a few ways to make different image sizes fit into a container. One is to use css background-image 'cover' which scales the image to the smallest possible size to fill the container. But the better way would be to use css object-fit, which wordier background-images, but for <img> tags. It has cover properties as well which work the same.

Loading off-screen images:

Most images on the carousel are never shown to the user, especially those at the back. It'd be a waste of bandwidth to load the all the images if they are not being shown.

Hence the images can be lazily loaded when they are on-screen. The  attribute defers loading images that aren't currently visible.

Also, use 'srcset' attribute on img tag to use optimized image sizes depending on the device screen size

<img srcset="/img/html/vangogh-sm.jpg 120w, /img/html/vangogh.jpg 193w, /img/html/vangogh-lg.jpg 278w"sizes="(max-width: 710px) 120px, (max-width: 991px) 193px, 278px">

Optimize list performance:

For better performance, we can render only the visible rows of content in a dynamic list instead of the entire list, which works by having a small container DOM element with relative positioning (window). Absolutely positioning children inside the container, setting their styles for top, left, width and height.

Other considerations:

Accessibility, Internationalization, Screen Readers, etc.



latte is a software developer based in California.

Leave a Reply

Related Posts