Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does "style.height/width" doesn't work with variables, only set values?

Currently trying to display a 16×16 grid using Flexbox and some DOM manipulation. This is the code that I would like to create a 16 block row inside the grid container:

// Gets grid's dimensions
const gridContainer = document.getElementById("grid-container");
const gridHeight = gridContainer.offsetHeight;
const gridWidth = gridContainer.offsetWidth;


function createBlock() {
  const gridBlock = document.createElement("div");
  gridBlock.style.height = gridHeight / 16;
  gridBlock.style.width = gridWidth / 16;
  gridBlock.style.border = "1px solid black";
  gridContainer.appendChild(gridBlock);
}

function createRow() {
  for (let i = 0; i < 16; i++) {
    createBlock();
  }
}

createRow();
#grid-container {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  background-color: #FFF;
  height: 40rem;
  width: 40rem;
}
<div id="grid-container"></div>

If I console.log gridBlock.style.height and width, the values are there, but they do not create a block.

If I set them to a fixed value like 40px, the code runs perfectly and the grid row is there as intended.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know that I can create them with CSS Grid and other methods, but Flexbox and DOM manipulation is what I’m learning ATM and this needs to be done using both. Any help is highly appreciated 🙂

>Solution :

You need to append a unit to the width/height, because unitless values for these properties don’t mean anything to CSS.

function createBlock() {
    const gridBlock = document.createElement("div");
    gridBlock.style.height = `${gridHeight / 16}px`;
    gridBlock.style.width = `${gridWidth / 16}px`;
    gridBlock.style.border = "1px solid black";
    gridContainer.appendChild(gridBlock);
}

If you’re coming from the React world, it is something that needs getting used to, as React intelligently casts numeric values to pixel values internally:

{/* Identical in React world */}
<div style={{ width: 16 }} />
<div style={{ width: '16px' }} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading