Horizontal scroll div container which snaps to elements using CSS scroll-snap-type. The code utilises overflow-y, overflow-behaviour-x, object-fit and scroll-snap-type. Sourced under a permissive license.

Horizontal scroll div container which snaps to elements using CSS scroll-snap-type

<div class="horizontal-snap">
  <a href="#"><img src="https://codesnippetsandtutorials.com/wp-content/uploads/2023/07/magicpattern-jbywvpa9vH8-unsplash-840x400.jpg"></a>
  <a href="#"><img src="https://codesnippetsandtutorials.com/wp-content/uploads/2023/07/magicpattern-jbywvpa9vH8-unsplash-840x400.jpg"></a>
  <a href="#"><img src="https://codesnippetsandtutorials.com/wp-content/uploads/2023/07/magicpattern-jbywvpa9vH8-unsplash-840x400.jpg"></a>
  <a href="#"><img src="https://codesnippetsandtutorials.com/wp-content/uploads/2023/07/magicpattern-jbywvpa9vH8-unsplash-840x400.jpg"></a>
  <a href="#"><img src="https://codesnippetsandtutorials.com/wp-content/uploads/2023/07/magicpattern-jbywvpa9vH8-unsplash-840x400.jpg"></a>
</div>

<style>
.horizontal-snap {
  margin: 0 auto;
  display: grid;
  grid-auto-flow: column;
  gap: 1rem;
  height: calc(180px + 1rem);
  padding: 1rem;
  max-width: 480px;
  overflow-y: auto;
  overscroll-behavior-x: contain;
  scroll-snap-type: x mandatory;
}

.horizontal-snap > a {
  scroll-snap-align: center;
}

.horizontal-snap img {
  width: 180px;
  max-width: none;
  object-fit: contain;
  border-radius: 1rem;
}
</style>

Tags: CSS, HTML, CSS, CSS code snippet, html code snippet, getelementbyid, javascript, horiztonal scroll div, css snap, overflow-y, overflow-behaviour-x, object-fit, scroll-snap-type

Image: Unsplash license

CC BY 4.0 added intro and tags – 30 Seconds of Code