What is Gap in JavaScript?
The gap property controls the space between grid items. In JavaScript, you access it simply
as gap (no camelCase needed - it's already one word!).
You can set gap in pixels, rem, em, percentages, or any CSS length unit. You can also set separate
horizontal and vertical gaps using columnGap and rowGap.
💡 Simple Property:
Unlike gridTemplateColumns, the gap property doesn't need camelCase because it has no
hyphens in CSS. It's just gap!
Basic Gap Usage
const container = document.getElementById('grid');
// 16px gap
container.style.gap = '16px';
// 1rem gap
container.style.gap = '1rem';
Row Gap and Column Gap
Set different spacing for rows vs columns:
// Different horizontal and vertical spacing
container.style.columnGap = '24px'; // horizontal
container.style.rowGap = '8px'; // vertical
⚡ Gap vs Margin:
Gap only affects space between items, not around the outer edges. Gap is cleaner for grids!
Dynamic Gap Based on Screen Size
function setResponsiveGap() {
const container = document.getElementById('grid');
if (window.innerWidth < 768) {
container.style.gap = '0.5rem';
} else {
container.style.gap = '2rem';
}
}
window.addEventListener('resize', setResponsiveGap);
Common Gap Values
Tight Layouts
container.style.gap = '0.5rem'; // 8px
Good for: Tag clouds, compact toolbars
Standard Layouts
container.style.gap = '1rem'; // 16px
Good for: Card grids, image galleries
Spacious Layouts
container.style.gap = '2rem'; // 32px
Good for: Hero sections, feature showcases
✅ Pro Tip:
Use rem units for gap! They scale with user's font size preferences (accessibility).
Complete Grid Setup
const container = document.getElementById('grid');
container.style.display = 'grid';
container.style.gridTemplateColumns = 'repeat(4, 1fr)';
container.style.gap = '1.5rem';
Level 1 Complete!
Congratulations! You've completed the basics of JavaScript Grid:
- ✅ How to enable grid with
display: 'grid' - ✅ Setting columns with
gridTemplateColumns - ✅ Controlling spacing with
gap
In Level 2, you'll learn how to make grids truly dynamic - changing layouts based on data, user interaction, and screen size!