What is Grid in JavaScript?
Instead of writing CSS Grid properties in a stylesheet, you can apply them directly through JavaScript using inline styles. This is useful for dynamic layouts, React components, and when you need to calculate or change grid properties programmatically.
In JavaScript, you access an element and set its style properties. For CSS Grid, you'll use
properties like display, gridTemplateColumns, gridTemplateRows,
and gap.
💡 Key Difference:
CSS properties with hyphens (like grid-template-columns) become camelCase in JavaScript
(gridTemplateColumns). This is standard for all CSS-in-JS!
Enabling Grid Display
First, you need to set display: 'grid' on an element:
// Get the element
const container = document.getElementById('myGrid');
// Enable grid display
container.style.display = 'grid';
That's it! The element is now a grid container. Items inside will follow grid rules.
Setting Grid Columns
Use gridTemplateColumns to define columns:
// Create 3 equal columns
container.style.gridTemplateColumns = '1fr 1fr 1fr';
// Or use repeat()
container.style.gridTemplateColumns = 'repeat(3, 1fr)';
Both create the same result: 3 columns that equally share available space.
Complete Example
Here's a full example creating a 3-column grid:
const container = document.getElementById('myGrid');
// Set grid properties
container.style.display = 'grid';
container.style.gridTemplateColumns = 'repeat(3, 1fr)';
container.style.gap = '1rem';
Values Must Be Strings
Important: All style values in JavaScript must be strings (in quotes):
// ✅ CORRECT
container.style.display = 'grid';
container.style.gap = '20px';
// ❌ WRONG
container.style.display = grid; // Error!
container.style.gap = 20px; // Error!
⚠️ Common Mistake:
Forgetting quotes is the #1 mistake. Always wrap values in quotes!
CSS vs JavaScript Property Names
display: grid→display = 'grid'grid-template-columns→gridTemplateColumnsgap→gap
Pattern: remove hyphens, capitalize the letter after each hyphen.