0

I have a react app where I'm creating about a million grid boxes, all the boxes ought to fit into the immediate screen (I want each box to be tiny asf). I'm using js to calculate each box's height and width in relation to the number of boxes.

var numOfBoxes = 1000 // this number can change anytime

var [height, width] = `${100/numberOfBoxes}%`

I created the grid using a CSS I found on StackOverflow

#root {
  width: 100vw;
  height: 100vh
}
// I tried to use vh and vw to make the #root element fit the initial screen


.square-container {
  display: flex;
  height: 100%;
  width: 100%;
  flex-wrap: wrap;
}

.square {
  position: relative;
  flex-basis: calc(25% - 10px);
  margin: 5px;
  border: 1px solid;
  box-sizing: border-box;
}

.square::before {
  content: '';
  display: block;
  padding-top: 100%;
}

.square .content {
  position: absolute;
  top: 0; left: 0;
  height: 100%;
  width: 100%;
}

But the squares remain the same size when I try to increase or decrease numOfBoxes. I tried changing the height and width from the DevTools but to no avail.

It looks like this if I render 100 boxes or 1000 grid

Can someone point me in the right direction?

Savvii
  • 480
  • 4
  • 9

1 Answers1

1

You can add a CSS variable to the root element, use it as part of the grid class, and then update it with setProperty.

// Using a setTimeout for this demo, but you would
// be adding this to your render method I expect
function changeWidth(width, count = 1) {
  document.documentElement.style.setProperty('--square-width', `${width}px`);
  if (count < 5) setTimeout(changeWidth, 2000, width +=5, ++count)
}

changeWidth(5);
:root {
  --square-width: 10px
}

.container {
  display: grid;
  grid-template-columns: repeat(3, var(--square-width));
  grid-gap: 5px;
}

.container div {
  background-color: red;
  aspect-ratio: 1;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
Andy
  • 61,948
  • 13
  • 68
  • 95