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 since it is 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.
gridTemplateColumns, the gap property does not need camelCase because it has no
hyphens in CSS. It is 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
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
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 have 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 will learn how to make grids truly dynamic: changing layouts based on data, user interaction, and screen size.