Search code examples
javascriptcssdomflexbox

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


Currently trying to display a 16x16 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.

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' }} />