Horizontally scroll to center an element

Posted on September 14, 2024 by Riccardo
<div class="width-full overflow-x-auto">
  <div>...</div>
  <div>element</div>
  <div>...</div>
</div>
const viewportWidth =
  Math.max(document.documentElement.clientWidth, window.innerWidth || 0)

container.scrollLeft =
  element.offsetLeft // scroll to the left edge of element
  + element.offsetWidth / 2 // scroll to center of element
  - viewportWidth / 2 // scroll back half the viewport

PinkLetter

It's one of the selected few I follow every week – Mateusz

Tired of RELEARNING webdev stuff?

  • A 100+ page book with the best links I curated over the years
  • An email once a week full of timeless software wisdom
  • Your recommended weekly dose of pink
  • Try before you buy? Check the archives.