JSFiddle - React, Tailwind, and code Playground

by kicken

HTML

<button type="button" id="add-front">
  Add div (front)
</button>
<button type="button" id="add-back">
  Add div (back)
</button>
<div class = "content"><div>1</div><div>2</div></div>

SCSS

.content
{
    position: absolute;
    top: 50px;;
    bottom: 50px;
    left: 20px;
    right: 20px;

    text-align: center;
    
    max-width: 100vw;
    margin: 0 auto;
    
    background: red;
    overflow: auto;
    white-space: nowrap;

    > div {
      display: inline-block;
      width: 40vw;
      height: 100%;
      background: orange;
      border: 1px solid purple;
      box-sizing: border-box;
      text-align: center;
      color: white;
      font-size: 22px;
    }
    
    > div:first-child{
      background: blue;
    }
    
    > div:last-child{
      background: green;
    }
}

JavaScript

window.addEventListener('DOMContentLoaded', () => {
  const content = document.querySelector(".content");
  document.getElementById('add-front').addEventListener('click', () => {
    const div = document.createElement("div")
    const currentScrollWidth = content.scrollWidth;
    content.insertBefore(div, content.firstChild);
    div.textContent=content.childElementCount;
    
    const offset = content.scrollWidth-currentScrollWidth;
  	content.scrollLeft+=offset;
    console.log(offset);
  });
  document.getElementById('add-back').addEventListener('click', () => {
    const div = document.createElement("div");
    content.appendChild(div);
    div.textContent=content.childElementCount;
  });
});