css grid 2column

by Sreeraj Saseendran

HTML

<div class="grid">
  <div class="item">Item 1 (tall)<br> Item 1 (tall) <br> Item 1 (tall)<br> Item 1 (tall)<br> Item 1 (tall)</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3 (taller)</div>
  <div class="item">Item 4</div>
  <div class="item">Item 5 (very tall)</div>
  <div class="item">Item 6</div>
</div>

CSS

.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-auto-rows: 10px;   /* base row height */
  gap: 20px;
}

.item {
  background: lightblue;
  padding: 16px;
  border: 1px solid #ccc;
}

JavaScript

function setMasonry(gridSelector) {
  const grid = document.querySelector(gridSelector);
  const rowHeight = parseInt(
    window.getComputedStyle(grid).getPropertyValue('grid-auto-rows')
  );
  const rowGap = parseInt(
    window.getComputedStyle(grid).getPropertyValue('gap')
  );

  grid.querySelectorAll('.item').forEach(item => {
    const itemHeight = item.getBoundingClientRect().height;
    const span = Math.ceil((itemHeight + rowGap) / (rowHeight + rowGap));
    item.style.gridRowEnd = `span ${span}`;
  });
}

// Initial call
setMasonry('.grid');

// Optional: recalc on window resize
window.addEventListener('resize', () => setMasonry('.grid'));