🔲

How to Use CSS Grid

HTML/CSSIntermediate

Build complex layouts with CSS Grid.

Code Example

HTML/CSS
<!DOCTYPE html>
<html>
<head>
<style>
  .grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    padding: 20px;
    font-family: sans-serif;
  }
  .item {
    padding: 20px;
    border-radius: 8px;
    color: white;
    text-align: center;
    font-weight: bold;
  }
  .item:nth-child(1) { background: #ef4444; grid-column: span 2; }
  .item:nth-child(2) { background: #3b82f6; grid-row: span 2; }
  .item:nth-child(3) { background: #10b981; }
  .item:nth-child(4) { background: #f59e0b; }
  .item:nth-child(5) { background: #8b5cf6; grid-column: span 3; }
</style>
</head>
<body>
  <div class="grid">
    <div class="item">Span 2 cols</div>
    <div class="item">Span 2 rows</div>
    <div class="item">Normal</div>
    <div class="item">Normal</div>
    <div class="item">Span all 3 cols</div>
  </div>
</body>
</html>

Explanation

CSS Grid uses display:grid. Define columns with grid-template-columns. Use grid-column and grid-row to span items.

Related Tutorials