0
0
CSSmarkup~5 mins

Grid container in CSS

Choose your learning style9 modes available
Introduction

A grid container helps you arrange items neatly in rows and columns, like a table but more flexible.

When you want to create a photo gallery with rows and columns.
When you need a layout with header, sidebar, main content, and footer.
When you want to align items evenly in both directions.
When you want to build a responsive design that changes layout on different screen sizes.
Syntax
CSS
selector {
  display: grid;
  grid-template-columns: value;
  grid-template-rows: value;
  gap: value;
}

display: grid; turns an element into a grid container.

You define columns and rows with grid-template-columns and grid-template-rows.

Examples
This creates 3 columns each 100 pixels wide.
CSS
.container {
  display: grid;
  grid-template-columns: 100px 100px 100px;
}
This creates 3 columns where the middle column is twice as wide as the others.
CSS
.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
}
This creates 4 equal columns with 10 pixels gap between items.
CSS
.container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}
Sample Program

This example creates a grid container with three columns. The middle column is twice as wide as the others. Each item is styled with a blue background and white text. The grid has gaps between items and padding around the container.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Grid Container Example</title>
  <style>
    .grid-container {
      display: grid;
      grid-template-columns: 1fr 2fr 1fr;
      gap: 1rem;
      padding: 1rem;
      background-color: #f0f0f0;
    }
    .grid-item {
      background-color: #4a90e2;
      color: white;
      padding: 1rem;
      text-align: center;
      border-radius: 0.5rem;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <main>
    <section class="grid-container" aria-label="Example grid container">
      <div class="grid-item">Item 1</div>
      <div class="grid-item">Item 2</div>
      <div class="grid-item">Item 3</div>
    </section>
  </main>
</body>
</html>
OutputSuccess
Important Notes

Use gap to add space between grid items easily.

Grid containers automatically place items in rows and columns based on your settings.

Try resizing the browser to see how grid adapts if you use flexible units like fr.

Summary

A grid container uses display: grid; to arrange items in rows and columns.

You control the layout with grid-template-columns and grid-template-rows.

Grid makes it easy to build neat, flexible, and responsive layouts.