0
0
CSSmarkup~5 mins

Why grid is needed in CSS

Choose your learning style9 modes available
Introduction

Grid helps arrange things neatly on a page in rows and columns. It makes building layouts easier and cleaner.

When you want to create a photo gallery with rows and columns.
When you need a webpage layout with header, sidebar, main content, and footer.
When you want items to line up evenly without guessing sizes.
When you want a design that adjusts nicely on different screen sizes.
Syntax
CSS
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
}
Use display: grid; on the container to start using grid layout.
grid-template-columns sets how many columns and their widths.
Examples
This creates three columns with fixed widths.
CSS
.container {
  display: grid;
  grid-template-columns: 100px 200px 100px;
}
This creates four equal columns that share space equally.
CSS
.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}
This creates three columns where the middle one is twice as wide as the others.
CSS
.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
}
Sample Program

This example shows six boxes arranged in three equal columns using CSS Grid. The boxes have space between them and are centered on the page.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Grid Example</title>
  <style>
    .grid-container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 1rem;
      max-width: 600px;
      margin: 2rem auto;
      padding: 1rem;
      border: 2px solid #333;
    }
    .grid-item {
      background-color: #4CAF50;
      color: white;
      padding: 1rem;
      text-align: center;
      font-size: 1.2rem;
      border-radius: 0.5rem;
    }
  </style>
</head>
<body>
  <main>
    <section class="grid-container" aria-label="Simple grid layout">
      <div class="grid-item">Box 1</div>
      <div class="grid-item">Box 2</div>
      <div class="grid-item">Box 3</div>
      <div class="grid-item">Box 4</div>
      <div class="grid-item">Box 5</div>
      <div class="grid-item">Box 6</div>
    </section>
  </main>
</body>
</html>
OutputSuccess
Important Notes

Grid is powerful for building complex layouts without extra code.

It works well with responsive design to adjust layouts on different screens.

Use browser DevTools to see grid lines and understand how items are placed.

Summary

Grid helps organize content in rows and columns easily.

It saves time and makes layouts cleaner and more flexible.

Grid works well for both simple and complex webpage designs.