Home > Net >  Add missing squares when div is resized
Add missing squares when div is resized

Time:10-07

I want to create a div, which has many smaller squares inside of it as such:

enter image description here

The problem is, is that when I resize my screen, the squares re-adjust making the rows uneven:

enter image description here

In that image, I could add 4 more squares, and the div is filled again equally with squares.

So I am wondering how would I add the missing squares on resize.

Here is a jsfiddle of my project

below is my code laid out:

const container = document.querySelector(".container");
  
for (let i = 1; i <= 20; i  ) {
    
    // create dom elem
    const square = document.createElement("div");
    square.setAttribute("class", "square");
    
    container.appendChild(square);

  }
.container {
  border: 3px solid black;
  width: 50%;
  height: 50%;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  justify-content: center;
  padding: 10px;
  gap: 10px;
}

.square {
  min-width: 40px;
  min-height: 40px;
 
 
 background-color: black;
}
<div >
  
</div>

CodePudding user response:

Add flex-grow: 1; on the item (the .square) see if the result fits your needs

CodePudding user response:

Not sure if that what you want but this code will let u keep constant number of rows of boxes with constant size for each box

const container = document.querySelector(".container");
const boxWidth = 40;
const gap = 10;
const padding = 10;
const numberOfRows = 4;
let numberOfBoxes = 0;

window.addEventListener("resize", (e) => {
    renderBoxes();
});

function renderBoxes() {
    const containerWidth = container.clientWidth;
    const boxesPerRow = ~~((containerWidth - padding) / (boxWidth   padding));
    const n = boxesPerRow * numberOfRows;
    if (n != numberOfBoxes) {
        container.innerHTML = "";
        for (let i = 1; i <= n; i  ) {
            const square = document.createElement("div");
            square.setAttribute("class", "square");
            container.appendChild(square);
        }
    }
}
renderBoxes();

padding constant refers to padding in one side only, the rest are clear

  • Related