Mileta Dulovic
HomeBlogReact

I am not sure if you knew, but you can utilize horizontal scroll and flexbox to create awesome carousel with just CSS and a bit of HTML.

Steps

  1. Set slides in flexbox and don't let them wrap
  2. Make the parent scrollable
  3. Line up the slides with scroll-snap-type
  4. Use scroll-snap-stop to scroll slides 1 by 1
<div class="slides-container">
  <div class="slide">1</div>
  <div class="slide">2</div>
  <div class="slide">3</div>
  <div class="slide">4</div>
  <div class="slide">5</div>
  <div class="slide">6</div>
</div>
.slides-container {
  display: flex;
  overflow: auto;
  flex: none;
  flex-flow: row nowrap; /* sets the flex flow to row, and forbid children from wrapping */
  scroll-snap-type: x mandatory; /* this allow us to snap the items when they are scrolled */
  width: 100%;
  gap: 20px;
  height: 200px;
}

.slides-container::-webkit-scrollbar {
  display: none;
}

.slides-container .slide {
  scroll-snap-stop: always; /* with this user scroll slides one by one, and can't skip them */
  scroll-snap-align: center;
  flex: none;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background-color: skyblue;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 80px;
  font-weight: bold;
  color: #fff;
}

Example

Here is the example that you can play with. Try changing code and see what happens.


import "./style.css";

const App = () => {
  return (
    <div class="slides-container">
      <div class="slide">1</div>
      <div class="slide">2</div>
      <div class="slide">3</div>
      <div class="slide">4</div>
      <div class="slide">5</div>
      <div class="slide">6</div>
    </div>
  )
}

export default App

Note

You can drag this carousel with mouse, as that would require JavaScript logic.

More in this category

CSS new :has selector

Want to know more about new awesome selector added in CSS? Let us dive right in!

Tailwind. Why and why not?

Let us talk about Tailwind. Do you really need to use it, and does it actually helps you.