JSFiddle - React, Tailwind, and code Playground

by sridhar reddy

HTML

<div class="wrapper">

</div>

<button id="add-box">
Add box
</button>

CSS

* {
  box-sizing: border-box;
}
.wrapper {
  display: grid;
  column-gap: 10px;
  padding: 10px 0;
  width: 700px;
  border: 2px solid #000;
  border-radius: 12px;
  background-color: #009688;
  grid-auto-columns: min-content;
  visibility: hidden;
}

div:not(.wrapper) {
  border-radius: 6px;
  border: 2px solid #000;
  height: 100px;
  background: yellow;
  position: relative;
}
div:not(.wrapper)::before {
  position: absolute;
  content: ' ';
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.1);
  top: 10px;
  left: 10px;
  border-radius: 4px;
}
div.wrapper:has(> div) {
  visibility: visible;
}
button {
  margin-top: 12px;
}

JavaScript

const container = document.querySelector('.wrapper');
let boxesAdded = 0;
let row = 1, col = 1;
const addBox = () => {
	const box = document.createElement('div');
	const boxCol = boxesAdded % 4;
  let isEnd = false;
	switch (boxCol) {
  	case 1:
    	box.style.width = '150px';
      break;
    case 2:
    	box.style.width = '100px';
      break;
    case 3:
    	box.style.width = '250px';
      box.style['grid-row'] = `${row + 1} / ${row + 2}`;
      break;
    default:
    	box.style.width = '150px';
      isEnd = true;
      break;
  }
  col += 1;
  if (boxCol !== 3) {
  	box.style['grid-row'] = `${row} / ${row + 1}`;
  }
  box.style['grid-column'] = `${col} / ${col+1}`;
  container.appendChild(box);
  if(isEnd) {
		col = 1;
    row += 2;
  }
}

const handleAddBox = () => {
	boxesAdded += 1;
  addBox();
}


const addBoxBtn = document.querySelector('#add-box');
addBoxBtn.addEventListener('click', handleAddBox)