目前正在尝试使用Flexbox和一些DOM操作来显示一个16x16的网格。这是我想在网格容器中创建一个16块行的代码:
// 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>
如果我使用console.log gridBlock. style. height and width,**这些值都在那里,**但它们不会创建一个块。
如果我将它们设置为一个固定值,比如40px,那么代码将完美地运行,网格行也将按预期显示在那里。
我知道我可以用CSS Grid和其他方法创建它们,但Flexbox和DOM操作是我正在学习的ATM,这需要同时使用两者。任何帮助都是非常感谢的:)
2条答案
按热度按时间aij0ehis1#
您需要向width/height附加一个单位,因为这些属性的无单位值对CSS没有任何意义。
如果您来自React世界,则需要习惯这一点,因为React会在内部智能地将数值转换为像素值:
toe950272#
既然你说你想学习CSS,你可以用一个类和一些
calc()
来做这件事,我在这里为边框和背景添加了一些颜色,只是为了显示它的工作。