← Back to Learning Path JavaScript • Level 1 • Lesson 3 of 9
Level 1 progress 0% complete

Lesson 3: Gap in JavaScript

Control spacing between grid items using the gap property.

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.

Simple Property Unlike 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
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 the 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 have completed the basics of JavaScript Grid:

In Level 2, you will learn how to make grids truly dynamic: changing layouts based on data, user interaction, and screen size.

Quick Check

Test your knowledge before completing Level 1. All 3 questions must be correct to continue.

1. How do you set a 16px gap?

2. What is the benefit of using rem units for gap?

3. How do you set different horizontal and vertical gaps?

← Previous Lesson