CSS overflow carousel example

CSS carousel example with overflow, ::scroll-button, and ::scroll-marker. The browser paints the controls. No slider library.

The problem

Carousels and sliders are common UI patterns, but they are often implemented with JavaScript or third-party libraries. This can lead to performance issues, accessibility challenges, and increased complexity in the codebase. A CSS-only solution can provide a more efficient and maintainable approach.

The method

By leveraging CSS properties like scroll-snap-type, ::scroll-button, and ::scroll-marker, we can create a fully functional carousel without relying on JavaScript. This approach allows for smooth scrolling, snap points, and visual indicators for navigation, all while keeping the DOM structure simple and accessible.

The stage

  • 01

    overflow

    The row can move.

  • 02

    scroll-snap

    It stops on a slide.

  • 03

    ::scroll-button

    The browser draws the control.

  • 04

    ::scroll-marker

    A dot for each item.

  • 05

    :target-current

    The active dot fills in.

  • 06

    scroll-marker-group

    The dots sit together.

The example


  
  • overflow
  • scroll-snap
.carousel {
  position: relative;
}

.carousel ul {
  display: flex;
  gap: 0.75rem;
  margin: 0;
  padding: 0;
  list-style: none;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  scroll-marker-group: after;
  scroll-behavior: smooth;
  scrollbar-width: none;
}

.carousel li {
  box-sizing: border-box;
  flex: 0 0 100%;
  min-height: 8rem;
  padding: 1.25rem 3rem;
  border: 1px solid #ccc;
  border-radius: 8px;
  background: #f6f6f6;
  scroll-snap-align: start;
}

.carousel ul::scroll-button(*) {
  position: absolute;
  top: 50%;
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 1px solid #ccc;
  border-radius: 8px;
  background: #fff;
  color: #111;
  font-size: 1.15rem;
  line-height: 1;
  cursor: pointer;
  translate: 0 -50%;
}

.carousel ul::scroll-button(*):disabled {
  opacity: 0;
}

.carousel ul::scroll-button(left) {
  content: "‹" / "Previous";
  left: 0.5rem;
}

.carousel ul::scroll-button(right) {
  content: "›" / "Next";
  right: 0.5rem;
}

.carousel ul::scroll-marker-group {
  display: flex;
  justify-content: center;
  gap: 0.4rem;
  margin-top: 0.75rem;
}

.carousel li::scroll-marker {
  content: "" / attr(data-label);
  width: 0.5rem;
  height: 0.5rem;
  border: 1px solid #111;
  border-radius: 50%;
  background: transparent;
  cursor: pointer;
}

.carousel li::scroll-marker:target-current {
  background: #111;
}

All Web API labs

  • CSS Anchor Positioning example
  • Customizable select example
  • CSS Custom Highlight API example