gpt4 book ai didi

javascript - div 行下方的空格

转载 作者:行者123 更新时间:2023-11-30 19:23:57 24 4
gpt4 key购买 nike

我正在尝试使用 JavaScript 创建一个简单的 10x10 网格。但是输出一直在 div 下显示空白。

首先创建 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>

最佳答案

row-div 是一个 block 元素,没有文本,但有一个 line-height,所以高度是一些违反直觉的值。来自 MDN :

On block-level elements, it specifies the minimum height of line boxes within the element.

可以通过以下方式修复:

  • a) 插入内联内容,例如div.innerText = 'a'(如果您打算在那里放置实际文本)
  • b) 显式设置 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>

关于javascript - div 行下方的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57124452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com