我正在尝试使用JavaScript创建一个简单的10x10网格。但是输出始终在divs下显示空白。
首先创建div行,然后在每行内添加单元格。我使用display: inline-block
来对齐div。但是不明白为什么每一行下面都有空白。
function grid() {
let gridCount = 10;
const container = document.querySelector('.container');
for (let row = 0; row <= gridCount; row++) {
const gridRow = document.createElement('div');
for (let cell = 0; cell <= gridCount; cell++) {
const div = document.createElement('div');
div.style.display = 'inline-block';
div.style.height = '0';
div.style.width = '5%';
div.style.paddingBottom = '5%';
div.style.border = ('1px solid black');
div.style.backgroundColor = ('lightpink');
gridRow.appendChild(div);
}
container.appendChild(gridRow);
}
}
grid();
html,
body {
height: 100%;
}
section.container {
height: 100%;
display: block;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Grid</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section class="container">
</section>
<script src="app.js"></script>
</body>
</html>
答案 0 :(得分:1)
row-div是一个没有文本,但带有line-height
的块元素,因此高度将是一些违反直觉的值。来自MDN:
在块级元素上,它指定元素内线框的最小高度。
它可以通过以下方式解决:
div.innerText = 'a'
(如果您打算在那里有实际的文字)gridRow.style.lineHeight = 0;
function grid() {
let gridCount = 10;
const container = document.querySelector('.container');
for (let row = 0; row <= gridCount; row++) {
const gridRow = document.createElement('div');
gridRow.style.lineHeight = 0;
for (let cell = 0; cell <= gridCount; cell++) {
const div = document.createElement('div');
div.style.display = 'inline-block';
div.style.height = '0';
div.style.width = '5%';
div.style.paddingBottom = '5%';
div.style.border = ('1px solid black');
div.style.backgroundColor = ('lightpink');
gridRow.appendChild(div);
}
container.appendChild(gridRow);
}
}
grid();
html,
body {
height: 100%;
}
section.container {
height: 100%;
display: block;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Grid</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section class="container">
</section>
<script src="app.js"></script>
</body>
</html>
答案 1 :(得分:0)
这很奇怪,我不知道空格是从哪里来的,但是如果将行显示设置为flex,就可以修复它
gridRow.style.display = 'flex';