Carousel Example
Carousel Example

How to Create a Carousel with HTML, CSS, and JavaScript: Step-by-Step Guide.

Pietro Gonçalves
6 min readMar 14, 2023

--

A carousel is a widely used element in user interfaces to display content in an organized and interactive way. These carousels allow users to navigate between different content elements, whether they are images, texts, or cards, in a fluid and engaging manner.

In this article, we will see how to create a Card Carousel using only HTML and CSS, without the need for external libraries or frameworks. This skill is highly valued in the job market, especially for front-end developers who want to create responsive and efficient interfaces.

We will cover the necessary steps for creating the HTML structure, styling with CSS, adding animation and control with JavaScript, in a clear and didactic way. With this knowledge, you will be able to create your own carousels, adapting them to different projects and needs.

For this, basic knowledge of HTML, CSS, and JavaScript is required. Additionally, we will need a code editor of your choice, such as Visual Studio Code or Sublime Text.

Let’s get started!

Preparing the Environment!

Before we start creating the carousel, we need to prepare the development environment.

Let’s start by creating the basic HTML structure for our carousel. We can begin with a div that will wrap the entire carousel, and within it, we will create another div for the cards. For example:

<div class="carousel">
<div class="card-container">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
<div class="card">Card 4</div>
<div class="card">Card 5</div>
</div>
</div>

With this basic structure created, we can move on to styling with CSS. It is important to remember that, to ensure the responsiveness of the carousel on different devices, it is necessary to use responsive design techniques, such as the use of media queries.

Styling the Carousel!

With the basic HTML structure created, let’s now style the card carousel using CSS. It is important to remember that the styling properties will depend on the layout and appearance you want to create for your carousel, but here are some tips to get started.

We can start by defining the size of the “carousel” div that wraps the entire carousel.

.carousel {
width: 100%; /* Width of carousel */
height: 166px; /* Height of carousel */
}

Next, let’s style the div that will contain the cards. We can use the “flex” property to position them side by side within the “card-container” div:

.card-container {
width: 100%; /* Width of card container */
display: flex; /* Set inline elements */
}

.card {
min-width: 250px; /* Set min width of card */
height: 150px; /* Set height of card */
}

Now let’s add the CSS properties that are responsible for the carousel behavior:

.card-container {
/* ... */
overflow-x: auto; /* Set overflow in horizontal scroll */
overflow-y: hidden; /* Hidden overflow in vertical scroll */
scroll-snap-type: x mandatory; /* Force the scroll to snap to the start of a scroll-snap area */
gap: 8px; /* Set gap between cards */
}

.card {
/* ... */
scroll-snap-align: start; /* Set the element focus position in scroll container */
}
Carousel Example
Carousel Project Example

To create the carousel behavior, our “card-container” uses the scroll-snap-typeproperty, which defines how an element scrolls and stops at specific points along the way. For example, if you have a container that scrolls, you can use this property to ensure it stops exactly where you want it to. It’s like a “glue” that keeps things in place as you scroll left or right.

And our “card” element uses the scroll-snap-alignproperty, which defines where an element should “snap” to in a scrolling container. It controls where the element will stop when you scroll the container. You can choose where the element will snap in the container, both vertically and horizontally. If you don’t specify a value for one axis, it will assume the same value as the other. For example, if you set scroll-snap-align: center, it will center the element vertically and horizontally in the container when you stop scrolling.

Let’s make it prettier!

At this point, the uniqueness of each project comes into play, as it’s time to bring the carousel style to life. Here’s an example:

.card-container {
/* ... */
width: calc(100% - 16px);
margin: 8px;
flex: 0 0 calc(100% - 16px); /* Set width of card container */
}

.card-container::-webkit-scrollbar {
display: none; /* Hide scrollbar in Chrome, Safari and Opera */
}

.card {
/* ... */
display: flex;
justify-content: center;
align-items: center;
background:#17BF60;
border: 1px solid #4F5873;
color: #4a544c;
border-radius: 8px;
}

.card:hover {
background: #1ED96F; /* Set background color when hover */
}
Carousel Example
Carousel Project Example

Adding click to focus

Now it’s time to add our beloved JavaScript. We will add an event listener for a click to set the scroll position to the focused card.

const listOfCardElements = document.querySelectorAll('.card');
const cardContainer = document.querySelector('.card-container');

listOfCardElements.forEach((cardElement, index) => {
cardElement.addEventListener('click', () => {
const scrollLeft = index * listOfCardElements[0].offsetWidth;
cardContainer.scrollTo({ left: scrollLeft, behavior: 'smooth' });
});
});
Carousel Example
Carousel Project Example

We added a click event to a set of elements with the CSS class “card” and scroll the horizontal container to the corresponding card element when it is clicked.

const scrollLeft = index * listOfCardElements[0].offsetWidth;
Calculates the amount of pixels the container needs to scroll to display the corresponding card element. The horizontal offset is calculated by multiplying the element’s index by its width. The offsetWidth property retrieves the total width of the element, including its margins and paddings.

cardContainer.scrollTo({ left: scrollLeft, behavior: 'smooth' });
Use the scrollTo method of the cardContainer element to scroll the container horizontally to the position specified by scrollLeft. The behavior property is set to "smooth" to scroll smoothly.

In Conclusion

Creating a carousel with HTML, CSS, and JavaScript can be a valuable skill for front-end developers who want to create engaging and responsive interfaces. This article provided a step-by-step guide to create a card carousel, covering the necessary steps for creating the HTML structure, styling with CSS, adding animation and control with JavaScript, in a clear and didactic way. By following these steps, one can create their own carousels, adapting them to different projects and needs. Additionally, the article discussed responsive design techniques and demonstrated how to use properties like “scroll-snap-type” and “scroll-snap-align” to make the carousel more engaging. Finally, the article showed how to add a click event listener to set the scroll position to the focused card.

Project in GitHub:
https://github.com/Pietrogon/carousel-example

My LinkedIn
https://www.linkedin.com/in/pietrogon

Referencing

  1. “flex” property: The Mozilla Developer Network (MDN) website is a great source to learn more about CSS properties, including “flex”. You can find more information here: https://developer.mozilla.org/en-US/docs/Web/CSS/flex
  2. Media queries: The MDN website also has a comprehensive guide on how to use media queries in CSS. You can find more information here: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries
  3. “scroll-snap-type” property: The MDN documentation is also a good place to start learning about this CSS property. You can find more information here: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-type
  4. “scroll-snap-align” property: The W3C website has a detailed specification on this CSS property. You can find more information here: https://www.w3.org/TR/css-scroll-snap-1/#scroll-snap-align-property

--

--

Pietro Gonçalves

I write software to improve business | FullStack Developer Java/React PL in Zallpy Digital