item scaling

by Jordan Sayner

HTML

<div class="container">
  <div class="scale-wrapper">
    <div class="items">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <!-- More items as needed -->
    </div>
  </div>
</div>

CSS

* {
  box-sizing: border-box;
}

html, body {
  height: 100%;
  margin: 0;
  overflow: hidden; /* Optional: prevents scrollbars */
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* Full screen height */
}

.scale-wrapper {
  display: flex;
  justify-content: center; /* Center the items */
  transition: transform 0.2s ease-out; /* Smooth transition on resize */
}

.items {
  display: flex;
}

.item {
  width: 100px; /* Fixed width for each item */
  height: 100px;
  background-color: #3498db;
  margin: 10px;
  border-radius: 10px;
}

JavaScript

function scaleContainer() {
  const container = document.querySelector('.items');
  const scaleWrapper = document.querySelector('.scale-wrapper');
  const containerWidth = container.scrollWidth; // Total width of the children
  const parentWidth = scaleWrapper.parentElement.clientWidth; // Width of the screen / parent

  const scale = parentWidth < containerWidth ? parentWidth / containerWidth : 1; 
  scaleWrapper.style.transform = `scale(${scale})`; 
  scaleWrapper.style.transformOrigin = 'center center'; // This ensures it scales from the center
}

// Run on load
scaleContainer();

// Run on resize
window.addEventListener('resize', scaleContainer);