我正在尝试创建一堆显示在固定大小容器 div 内的 div。使用 javascript 我可以创建我想要的 div 数量。我的问题是 div 不适合水平或垂直放置在容器中。容器 div 的高度和宽度应为 1000px,我在 css 中设置,但它的高度和宽度为 1002px,这是我在检查页面后意识到的。较小的正方形的高度和宽度也增加了 2 像素,这意味着超过 1x1 网格的任何内容都无法放入容器中。我真的不确定为什么会发生这种情况。任何帮助将不胜感激。
链接到jsfiddle: https://jsfiddle.net/wrjo38t5/
HTML:
<body>
<button type="button">Reset</button>
<div id= "container">
</div>
<script src="jQuery.js"></script>
<script src="javascript.js"></script>
</body>
CSS:
div {
border: 1px dashed black;
height: 1000px;
width: 1000px;
font-size: 0;
}
.square{
float: left;
font-size: 0;
border: 1px dashed red;
display: inline-block;
}
Javascript:
var gridSize = prompt("Enter size of grid:");
gridSize = Number(gridSize);
createGrid(gridSize);
function createGrid(gridSize){
//setting up variables
var newSize = 1000/gridSize;
var j = 1;
var i = 1;
var cont = document.getElementById('container');
//loop to add a column square
while(i<=gridSize){
var sketchSquare = document.createElement('div');
sketchSquare.className= "square";
sketchSquare.style.width= newSize + "px";
sketchSquare.style.height= newSize + "px";
cont.appendChild(sketchSquare);
//if statement to add new row
if (i === gridSize && j < gridSize) {
j++;
i = 0;
}
i++;
}
}
最佳答案
CSS border
添加宽度和高度。
尝试使用 outline
代替:
div {
outline: 1px dashed black;
height: 1000px;
width: 1000px;
font-size: 0;
}
.square{
float: left;
font-size: 0;
outline: 1px dashed red;
display: inline-block;
}
关于javascript - Div 无法放入其容器内,并且它们添加了像素。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36139561/