You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何style.height/width使用变量无效,仅固定值生效?(Flexbox+DOM场景)

解决Flexbox+DOM操作创建16×16网格时方块不显示的问题

问题出在你设置方块宽高时没有添加单位:

  • offsetHeight和offsetWidth返回的是纯数字(默认单位为像素),直接把gridHeight / 16这种数字赋值给style.height/style.width,浏览器无法识别这个尺寸,导致方块实际没有宽高,自然看不到。
  • 而你用40px能正常显示,是因为带了明确的单位,浏览器能解析。

修正方案

  1. 给计算后的宽高添加px单位
  2. 给方块加上box-sizing: border-box,让边框包含在宽高内,避免16个方块的边框总宽度超出容器

修正后的完整代码:

JavaScript

// 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");
  // 添加px单位
  gridBlock.style.height = `${gridHeight / 16}px`;
  gridBlock.style.width = `${gridWidth / 16}px`;
  gridBlock.style.border = "1px solid black";
  // 让边框包含在宽高内
  gridBlock.style.boxSizing = "border-box";
  gridContainer.appendChild(gridBlock);
}

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

createRow();

CSS

#grid-container {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  background-color: #FFF;
  height: 40rem;
  width: 40rem;
  /* 可选:给容器加边框方便观察 */
  border: 1px solid #eee;
}

HTML

<div id="grid-container"></div>

这样修改后,方块就能正常显示,且不会超出容器范围。

内容的提问来源于stack exchange,提问作者Jinzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:02:11