65 Mins

13. CSS Grid

CSS Layouts

Flexbox handles one dimension (a row or a column). CSS Grid handles two dimensions simultaneously — rows AND columns at the same time. Use it for page layouts, dashboards, galleries, and bento boxes.

Basic Grid

<style> .grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; padding: 10px; background: #f5f5f5; } .cell { background: #4FC3F7; color: white; padding: 20px; text-align: center; border-radius: 6px; font-family: sans-serif; font-weight: bold; } </style> <div class="grid"> <div class="cell">1</div> <div class="cell">2</div> <div class="cell">3</div> <div class="cell">4</div> <div class="cell">5</div> <div class="cell">6</div> </div>

Spanning Columns

<style> .grid2 { display:grid; grid-template-columns:1fr 1fr 1fr; gap:8px; padding:8px; } .cell2 { background:#66bb6a; color:white; padding:20px; text-align:center; border-radius:6px; font-family:sans-serif; font-weight:bold; } .span2 { grid-column: span 2; background:#ff7043; } .span3 { grid-column: span 3; background:#ab47bc; } </style> <div class="grid2"> <div class="cell2 span3">Full width (spans 3)</div> <div class="cell2 span2">Spans 2 columns</div> <div class="cell2">1</div> <div class="cell2">1</div> <div class="cell2">1</div> <div class="cell2">1</div> </div>

Photo Gallery

<style> * { box-sizing: border-box; margin: 0; padding: 0; } .gallery { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; padding: 8px; background: #111; } .gallery img { width: 100%; height: 120px; object-fit: cover; border-radius: 4px; display: block; } .gallery img:first-child { grid-column: span 2; } </style> <div class="gallery"> <img src="https://picsum.photos/seed/a/400/200" alt="Wide photo"> <img src="https://picsum.photos/seed/b/200/120" alt="Photo"> <img src="https://picsum.photos/seed/c/200/120" alt="Photo"> <img src="https://picsum.photos/seed/d/200/120" alt="Photo"> <img src="https://picsum.photos/seed/e/200/120" alt="Photo"> </div>

Knowledge Check

Ready to test your understanding of 13. CSS Grid?

Back