My goal is to create a grid of square "pixels" (div elements) that automatically scales the pixels to match the width of the page (up to max-width: 800px
).
I want to implement this using CSS in a way that is "agnostic" to the number of rows and columns in the grid. This rules out using CSS display: grid
, for example.
Here is my attempt:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pixel grid</title>
<style>
#container {
max-width: 800px;
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 8px;
}
.pixel-row {
display: flex;
gap: 8px;
justify-content: space-between;
}
.pixel {
flex: 1;
border: 1px solid gray;
}
</style>
</head>
<body>
<div id="container"></div>
<!-- Script to generate row and column elements-->
<script>
// These numbers could change
const rows = 10;
const columns = 14;
for (let i = 0; i < rows; i++) {
newRow = document.createElement("div");
newRow.classList.add("pixel-row");
for (let j = 0; j < columns; j++) {
newPixel = document.createElement("div");
newPixel.classList.add("pixel");
newRow.appendChild(newPixel);
}
document.getElementById("container").appendChild(newRow);
}
</script>
</body>
</html>
As you can see in the following screenshot, this achieves the desired distribution of columns. But I cannot figure out how to make the height of the pixel div
s match their width.
How do I style the .pixel
s and .pixel-row
s so that the pixels have height matching their width?
Disclaimers
- I have seen various tutorials online for making these kinds of equally spaced pixel grids, but all of them were one step away from my specific problem, e.g. because they used a static number of rows/columns (meaning they could use
display: grid
ordisplay: flexbox
withflex-wrap
), or used a static pixel size (.pixel { width: 10px; height: 10px; }
) - For example, my question is distinct from this one because I only want the width of the grid to fit in the browser. If there are many rows, then the user should have to scroll vertically to see them.
- And my question is distinct from this one because that solution depends on there being exactly two columns.