Back to JavaScript
2026-03-156 min read

Grid Generator (JavaScript)

Learn Grid Generator (JavaScript) step by step with clear examples and exercises.

Why This Matters

In web development, creating grids is a fundamental skill for designing responsive and visually appealing layouts. The CSS Grid Layout module in JavaScript offers an efficient and intuitive approach to building complex grid systems without the need for predefined floats or tables. Understanding how to use this powerful feature will help you build modern, flexible websites that cater to various devices and screen sizes.

Prerequisites

To follow along with this lesson, you should have a basic understanding of:

  1. HTML (Hypertext Markup Language): Learn about creating web pages using semantic elements like `, , , and . Familiarize yourself with the structure of an HTML document, including the and ` sections.
  1. CSS (Cascading Style Sheets): Learn about styling web pages using CSS properties like color, font-size, margin, and padding. Familiarize yourself with the box model, specificity, inheritance, and the cascade.
  1. JavaScript (ES6 syntax): Learn about variables, functions, arrays, loops, conditionals, and objects in JavaScript. Familiarize yourself with modern ES6 features like arrow functions, template literals, destructuring assignment, and modules.
  1. Document Object Model (DOM): Learn about the DOM, which represents an HTML document as a tree-like structure of nodes and objects that can be manipulated using JavaScript. Familiarize yourself with common DOM methods like getElementById(), querySelector(), querySelectorAll(), and event handling.

Core Concept

Introduction to CSS Grid Layout

CSS Grid Layout is a two-dimensional system that allows for the creation of flexible, adaptable grids. It offers a more intuitive and efficient approach to designing layouts compared to traditional methods like floats or tables. The grid consists of rows and columns, which can be easily manipulated using CSS properties.

Defining a Grid Container (Expanded)

To create a grid container in your HTML, you'll first need to define a parent element with the display: grid property applied. This will transform the element into a grid container. You can also use the fr unit for flexible sizing of rows and columns.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grid Generator</title>
<style>
#grid-container {
display: grid;
/* Grid template rows and columns */
grid-template-rows: repeat(3, 1fr);
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
</style>
</head>
<body>
<div id="grid-container">
<!-- Grid items will be placed here -->
</div>
</body>
</html>

In the example above, we've created a grid container with 3 rows and 4 columns using the grid-template-rows and grid-template-columns properties. The gap property is also used to add space between grid items.

Placing Grid Items (Expanded)

To place grid items within the container, you can use the grid-row and grid-column properties. These properties allow you to specify the row and column that an element should start and end on. You can also use the grid-area property to define a single cell containing multiple rows and columns.

<div id="grid-container">
<div class="item" grid-row="1 / span 2" grid-column="1 / span 3">Item 1</div>
<!-- More items here -->
</div>

In the example above, we've created a grid item that spans across two rows (starting from row 1) and three columns (starting from column 1).

Grid Lines and Areas (Expanded)

Grid lines are the virtual lines that define the boundaries of each cell in the grid. You can use the grid-row-start, grid-row-end, grid-column-start, and grid-column-end properties to manipulate these lines. Grid areas allow you to create complex layouts by combining multiple rows and columns into a single cell. To define an area, use the grid-area property with the following format: grid-area: row-start / column-start / row-end / column-end.

Grid Templates (Expanded)

Grid templates are used to predefine the structure of your grid container. They allow you to specify the number and size of rows and columns, as well as areas if needed. You can use the grid-template shorthand property to define a template with both rows and columns or separate grid-template-rows and grid-template-columns properties for individual control.

Worked Example

In this example, we'll create a simple grid layout using CSS Grid Layout in JavaScript. We'll generate a 4x4 grid with random colors for each cell.

// Create the grid container
const gridContainer = document.getElementById('grid-container');

// Define the number of rows and columns
const numRows = 4;
const numColumns = 4;

// Generate the grid items with random colors
for (let row = 1; row <= numRows; row++) {
for (let col = 1; col <= numColumns; col++) {
const gridItem = document.createElement('div');
gridItem.style.backgroundColor = `hsl(${Math.random() * 360}, 50%, 50%)`;
gridItem.classList.add('item');
gridItem.setAttribute('grid-row', `${row} / span 1`);
gridItem.setAttribute('grid-column', `${col} / span 1`);
gridContainer.appendChild(gridItem);
}
}

In the example above, we've created a grid container and generated 4x4 grid items with random colors using JavaScript. We've also used the grid-row and grid-column properties to place each item in its respective cell.

Common Mistakes

Forgetting to set display: grid on the container

Ensure that you apply the display: grid property to your grid container element.

Not defining the number of rows and columns

Always define the number of rows and columns using either the grid-template-rows or grid-template-columns properties, or by using the grid-auto-rows and grid-auto-columns properties to let the browser determine their size.

Misusing grid lines and areas

When defining grid lines and areas, make sure that you use the correct property for each (e.g., grid-row-start, grid-column-end, or grid-area). Also, be aware of how the properties interact with each other when spanning multiple rows or columns.

Not considering responsiveness

Remember to make your grid adaptable to different screen sizes by using media queries and adjusting the number of rows and columns based on breakpoints.

### Common Mistakes (Expanded - Subheadings)

  • Forgetting to set display: grid on the container
  • Not defining the number of rows and columns
  • Misusing grid lines and areas
  • Using incorrect properties for grid lines and areas
  • Incorrectly spanning multiple rows or columns
  • Not considering responsiveness
  • Failing to use media queries
  • Ignoring breakpoints when adjusting the number of rows and columns
  • Overcomplicating grid layouts
  • Trying to create complex layouts without proper planning
  • Using too many nested grids unnecessarily

Practice Questions

  1. Create a 6x6 grid with alternating colors (red and blue) using CSS Grid Layout.

Solution:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grid Generator</title>
<style>
#grid-container {
display: grid;
grid-template-rows: repeat(6, 1fr);
grid-template-columns: repeat(6, 1fr);
gap: 10px;
}
.item:nth-child(odd) {
background-color: red;
}
.item:nth-child(even) {
background-color: blue;
}
</style>
</head>
<body>
<div id="grid-container">
<!-- Grid items will be placed here -->
</div>
</body>
</html>
  1. Given the following HTML structure:
<div id="grid-container">
<div class="item" id="a"></div>
<div class="item" id="b"></div>
<div class="item" id="c"></div>
</div>

Write the CSS to place #a in grid area "1 / 1", #b in grid area "2 / span 2", and #c in grid area "3 / span 2".

Solution:

#grid-container {
display: grid;
grid-template-areas:
"a a a a"
"b b b b"
"c c c c";
}
#a {
grid-area: 1 / 1 / 1 / 1;
}
#b {
grid-area: 2 / 1 / 4 / span 2;
}
#c {
grid-area: 3 / 1 / 5 / span 2;
}

FAQ

How do I create a responsive grid with CSS Grid Layout?

To make your grid adaptable to different screen sizes, you can use the minmax() function to set minimum and maximum values for rows and columns. You can also use media queries to apply different templates based on specific breakpoints.

Can I nest grids within other grids using CSS Grid Layout?

Yes, you can nest grids within other grids by placing a grid container inside another grid container and defining its properties accordingly. Keep in mind that nested grids can become complex, so it's essential to plan your layout carefully.

How do I center an element within a grid cell using CSS Grid Layout?

To center an element within a grid cell, you can use the justify-content and align-items properties for horizontal and vertical alignment, respectively. For example:

.item {
justify-content: center;
align-items: center;
}
Grid Generator (JavaScript) | JavaScript | XQA Learn