htmlcssflexbox

How to create an n x n grid of tiles with fixed container dimensions using CSS flexbox?


I'm trying to create an n x n grid of tiles that fit within a fixed container (800px x 700px). I managed to generate the correct number of tiles using JavaScript, but I’m having trouble aligning them perfectly in the container using CSS.

Each tile should automatically resize so that all n² tiles fit exactly in the container without overflowing, and they should form a perfect grid layout.

Here's my current code:

const btn = document.createElement("button");
const body = document.querySelector("body");
body.appendChild(btn);
btn.className = "button";
btn.textContent = "button";

const container = document.createElement("div");
container.className = "container";
body.appendChild(container);

btn.addEventListener("click", () => {
  let select = Number(prompt("수 입력: "));
  container.innerHTML = ""; // clear existing boxes

  for (let i = 0; i < select * select; i++) {
    const div = document.createElement("div");
    div.className = "box";
    div.style.width = `calc(800px / ${select})`;
    div.style.height = `calc(700px / ${select})`;
    container.appendChild(div);
  }
});
*::after,
*::before {
  box-sizing: border-box;
}

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  width: 800px;
  height: 700px;
  border: 3px solid black;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.box {
  border: 1px solid black;
}


Solution

  • const btn = document.createElement("button");
    const body = document.querySelector("body");
    body.appendChild(btn);
    btn.className = "button";
    btn.textContent = "button";
    
    const container = document.createElement("div");
    container.className = "container";
    body.appendChild(container);
    
    btn.addEventListener("click", () => {
      let select = Number(prompt("수 입력: "));
      container.innerHTML = ""; // clear existing boxes
    
      for (let i = 0; i < select * select; i++) {
        const div = document.createElement("div");
        div.className = "box";
        div.style.width = `calc(100% / ${select})`;
        div.style.height = `calc(100% / ${select})`;
        container.appendChild(div);
      }
    });
    *,
    *::after,
    *::before {
      box-sizing: border-box;
    }
    
    * {
      margin: 0;
      padding: 0;
    }
    
    html,
    body {
      height: 100%;
    }
    
    body {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .container {
      width: 800px;
      height: 700px;
      border: 3px solid black;
      overflow: hidden;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
    }
    
    .box {
      border: 1px solid black;
    }