I started off by creating a <div>
called snake-container
, which contains the division tiles, which is 500x500px. I then used a for loop in Javascript to put a 25x25px grid of 20x20px <div>
s with black backgrounds. However, instead of creating a grid like I wanted it created a long column of 625 <div>
s. It turns out each <div>
has a weird margin that stretches all the way from left to right within the .tiles
<div>
. I've set everything to 0 px margin, but these weird row-like margins remain. Why is this happening?
Here's the code:
<html>
<head>
<title>Snake</title>
</head>
<body>
<div id="snake-container">
<div id="tiles">
</div>
</div>
</body>
<script>
for (let i = 0; i < 625; i ) {
const tile = document.createElement("div");
tile.classList.add("tile");
document.getElementById("tiles").appendChild(tile);
}
</script>
<style>
* {
margin: 0px;
padding: 0px;
}
#snake-container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
}
#tiles {
width: 500px;
height: 500px;
}
.tile {
width: 20px;
height: 20px;
background-color: black;
margin: 0px;
}
</style>
</html>
CodePudding user response:
The reason for the space is that the justify-content
property is assigned a center
value. The image below shows the behavior of containers when the justify-content
property is set to a center
value.
The image below is a demonstration of the feature causing the gap in Chrome Dev Tools.
In the application below, the justify-content
property in the #snake-container
block has been removed.
<html>
<head>
<style>
* {
margin: 0px;
padding: 0px;
}
#snake-container {
width: 100%;
height: 100%;
display: flex;
}
#tiles {
width: 500px;
height: 500px;
}
.tile {
width: 20px;
height: 20px;
background-color: black;
}
</style>
<title>Snake</title>
</head>
<body>
<div id="snake-container">
<div id="tiles"></div>
</div>
</body>
<script>
for (let i = 0; i < 625; i ) {
const tile = document.createElement("div");
tile.classList.add("tile");
document.getElementById("tiles").appendChild(tile);
}
</script>
</html>