DevToolBoxฟรี
บล็อก

CSS Grid Layout: บทเรียนฉบับสมบูรณ์พร้อมตัวอย่างจริง

12 นาทีในการอ่านโดย DevToolBox

CSS Grid Layout: The Complete Tutorial for 2026

CSS Grid is the most powerful two-dimensional layout system available in CSS. Unlike Flexbox which handles one dimension at a time, Grid lets you control rows and columns simultaneously, making it ideal for page layouts, dashboards, galleries, and complex component structures. This tutorial covers every Grid property with practical examples you can use immediately.

Getting Started with Grid

To create a grid container, set display: grid on a parent element. Its direct children automatically become grid items. From there, you define the row and column structure.

.container {
  display: grid;
  grid-template-columns: 200px 1fr 200px;
  grid-template-rows: auto 1fr auto;
  gap: 16px;
}

/* inline-grid for inline-level containers */
.inline-container {
  display: inline-grid;
  grid-template-columns: 100px 100px;
}

Defining Columns and Rows

The grid-template-columns and grid-template-rows properties define the track sizes. You can mix fixed sizes, flexible units, percentages, and content-based sizing.

Fixed and Flexible Sizes

/* Fixed pixel widths */
grid-template-columns: 100px 200px 100px;

/* Flexible fr units — divide available space proportionally */
grid-template-columns: 1fr 2fr 1fr;
/* First and third columns get 1 share each, middle gets 2 shares */

/* Mix fixed and flexible */
grid-template-columns: 250px 1fr;
/* Sidebar at 250px, main content fills remaining space */

/* Percentage-based */
grid-template-columns: 25% 50% 25%;

/* Content-based sizing */
grid-template-columns: auto 1fr auto;
/* auto = sized to fit content */

repeat() Function

The repeat() function avoids writing the same track size multiple times.

/* 4 equal columns */
grid-template-columns: repeat(4, 1fr);

/* Pattern repetition */
grid-template-columns: repeat(3, 100px 1fr);
/* Expands to: 100px 1fr 100px 1fr 100px 1fr */

/* auto-fill: create as many tracks as fit */
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));

/* auto-fit: same as auto-fill but collapses empty tracks */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

minmax() Function

The minmax() function sets a minimum and maximum size for a track, enabling responsive layouts without media queries.

/* Columns at least 200px, at most 1fr */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

/* Rows at least 100px tall, grow with content */
grid-template-rows: minmax(100px, auto);

/* Combine with fixed tracks */
grid-template-columns: 250px minmax(300px, 1fr) 250px;

Grid Gap (Spacing)

The gap property controls spacing between grid tracks. Unlike margins, gaps only apply between items and not on the outer edges.

/* Equal row and column gaps */
gap: 16px;

/* Different row and column gaps */
gap: 20px 16px;  /* row-gap column-gap */

/* Individual properties */
row-gap: 20px;
column-gap: 16px;

Placing Items on the Grid

Grid items can be explicitly placed using line numbers, named lines, or named areas. By default, items flow automatically into the next available cell.

Line-Based Placement

/* Grid lines are numbered starting at 1 */
.item {
  grid-column-start: 1;
  grid-column-end: 3;   /* spans columns 1-2 */
  grid-row-start: 1;
  grid-row-end: 2;
}

/* Shorthand */
.item {
  grid-column: 1 / 3;   /* start / end */
  grid-row: 1 / 2;
}

/* Span syntax */
.item {
  grid-column: 1 / span 2;  /* start at 1, span 2 columns */
  grid-row: span 3;         /* span 3 rows from current position */
}

/* Negative lines count from the end */
.full-width {
  grid-column: 1 / -1;  /* spans entire row */
}

grid-area Shorthand

/* grid-area: row-start / col-start / row-end / col-end */
.header {
  grid-area: 1 / 1 / 2 / -1;  /* full width, first row */
}

.sidebar {
  grid-area: 2 / 1 / 4 / 2;   /* rows 2-3, first column */
}

.main {
  grid-area: 2 / 2 / 3 / 3;   /* row 2, second column */
}

Named Grid Areas

Named grid areas provide a visual, intuitive way to define layouts. Each string represents a row, and each word represents a cell. This is one of the most readable ways to define page layouts.

.container {
  display: grid;
  grid-template-columns: 250px 1fr 250px;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header  header  header"
    "sidebar main    aside"
    "footer  footer  footer";
  gap: 16px;
  min-height: 100vh;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.aside   { grid-area: aside; }
.footer  { grid-area: footer; }

/* Use . for empty cells */
grid-template-areas:
  "header header header"
  "sidebar main ."
  "footer footer footer";

Alignment and Justification

Grid provides six alignment properties that control how items are positioned within their cells and how tracks are distributed within the container.

Container Alignment

/* Align all items within their cells */
.container {
  /* Horizontal alignment of items within cells */
  justify-items: start | end | center | stretch;

  /* Vertical alignment of items within cells */
  align-items: start | end | center | stretch;

  /* Shorthand for both */
  place-items: center center;
}

/* Distribute tracks within the container */
.container {
  /* Horizontal distribution of columns */
  justify-content: start | end | center | space-between | space-around | space-evenly;

  /* Vertical distribution of rows */
  align-content: start | end | center | space-between | space-around | space-evenly;

  /* Shorthand */
  place-content: center space-between;
}

Item Self-Alignment

/* Override container alignment for individual items */
.item {
  justify-self: start | end | center | stretch;
  align-self: start | end | center | stretch;
  place-self: center end;  /* shorthand */
}

Implicit Grid and Auto Flow

When items are placed outside the explicit grid or there are more items than defined cells, the implicit grid creates additional tracks automatically.

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  /* Only 3 columns defined, but 9 items exist */

  /* Control implicit row sizing */
  grid-auto-rows: minmax(100px, auto);

  /* Control implicit column sizing */
  grid-auto-columns: 200px;

  /* Control auto-placement direction */
  grid-auto-flow: row;         /* default — fill rows first */
  grid-auto-flow: column;      /* fill columns first */
  grid-auto-flow: row dense;   /* fill gaps with smaller items */
}

Common Layout Patterns

Responsive Card Grid (No Media Queries)

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
}

/* Cards automatically wrap to new rows as viewport shrinks.
   Each card is at least 280px wide and stretches equally. */

Holy Grail Layout

.holy-grail {
  display: grid;
  grid-template-columns: 200px 1fr 200px;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header header"
    "nav    main   aside"
    "footer footer footer";
  min-height: 100vh;
  gap: 16px;
}

/* Responsive: stack on mobile */
@media (max-width: 768px) {
  .holy-grail {
    grid-template-columns: 1fr;
    grid-template-areas:
      "header"
      "nav"
      "main"
      "aside"
      "footer";
  }
}

Dashboard Layout

.dashboard {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: auto;
  gap: 16px;
}

/* Widgets span different numbers of columns */
.widget-wide    { grid-column: span 2; }
.widget-tall    { grid-row: span 2; }
.widget-full    { grid-column: 1 / -1; }
.widget-feature { grid-column: span 2; grid-row: span 2; }

Masonry-Like Layout

.masonry {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-auto-rows: 10px;
  gap: 16px;
}

/* Each item spans a different number of row tracks */
.masonry-item-small  { grid-row: span 15; }
.masonry-item-medium { grid-row: span 25; }
.masonry-item-large  { grid-row: span 35; }

Image Gallery

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-auto-rows: 200px;
  gap: 8px;
}

.gallery img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

/* Feature image spans 2x2 */
.gallery .featured {
  grid-column: span 2;
  grid-row: span 2;
}

Grid vs Flexbox: When to Use Each

FeatureCSS GridFlexbox
DimensionsTwo-dimensional (rows + columns)One-dimensional (row OR column)
Layout approachLayout-first (define structure, place items)Content-first (items determine layout)
Best forPage layouts, dashboards, galleriesNavigation bars, card internals, centering
Item sizingContainer controls sizingItems control sizing
Gap supportYesYes
OverlapItems can overlap with z-indexNo overlap support
Named areasYes (grid-template-areas)No

Rule of thumb: Use Grid for the overall page layout and Flexbox for component internals. They work best together, not as alternatives.

Browser Support

CSS Grid is supported in all modern browsers with over 97% global coverage. Features likegap, minmax(), auto-fit, and auto-fill have universal support. The subgrid feature is supported in Firefox 71+, Chrome 117+, Safari 16+, and Edge 117+.

Subgrid

Subgrid allows a grid item that is also a grid container to inherit the track sizing from its parent grid. This is essential for aligning nested grids to the parent layout.

.parent {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.child {
  display: grid;
  grid-column: span 3;
  /* Inherit parent column tracks */
  grid-template-columns: subgrid;
  /* Define own rows */
  grid-template-rows: auto auto;
}

/* Now child's items align perfectly to parent's columns */

Frequently Asked Questions

What is the difference between auto-fill and auto-fit?

Both create as many tracks as fit in the container. The difference appears when there are fewer items than tracks: auto-fill keeps the empty tracks (preserving their space), whileauto-fit collapses empty tracks to zero, allowing existing items to stretch and fill the available space.

Can I use CSS Grid for responsive design without media queries?

Yes. The combination of repeat(auto-fit, minmax(min, 1fr)) creates fully responsive grids. Items automatically wrap to new rows as the viewport shrinks, and each item maintains a minimum width. This is one of the most powerful CSS Grid patterns.

How do I center an item in CSS Grid?

The simplest way is to use place-items: center on the container, which centers all items both horizontally and vertically. For a single item, use place-self: center.

Can Grid items overlap?

Yes. When you place multiple items in the same grid area, they overlap. Use z-index to control the stacking order. This is useful for creating overlay effects, feature cards, and layered layouts.

Should I use Grid or Flexbox?

Use Grid when you need to control layout in two dimensions (both rows and columns). Use Flexbox when you are working with a single row or column of items. In practice, most pages use both: Grid for the overall page structure and Flexbox within individual components.

What is subgrid and when should I use it?

Subgrid lets a nested grid inherit track sizes from its parent. Use it when you need children of a grid item to align with the outer grid, such as card layouts where headings, content, and buttons should align across cards in different columns.

𝕏 Twitterin LinkedIn
บทความนี้มีประโยชน์ไหม?

อัปเดตข่าวสาร

รับเคล็ดลับการพัฒนาและเครื่องมือใหม่ทุกสัปดาห์

ไม่มีสแปม ยกเลิกได้ตลอดเวลา

ลองเครื่องมือที่เกี่ยวข้อง

{ }CSS Minifier / Beautifier🎨CSS Formatter

บทความที่เกี่ยวข้อง

CSS Grid Layout สูตรโกง

เชี่ยวชาญ CSS Grid ด้วยสูตรโกงแบบภาพ grid-template, gap, auto-fit, minmax() และรูปแบบ responsive

CSS Flexbox Cheat Sheet: ทุก Property อธิบายพร้อมตัวอย่าง

CSS Flexbox cheat sheet แบบภาพ ครอบคลุมทุก property พร้อมตัวอย่าง

CSS Flexbox คู่มือฉบับสมบูรณ์: ทุก Property และ Layout Pattern

เชี่ยวชาญ CSS Flexbox: คู่มือสมบูรณ์ property ทั้ง container และ item พร้อมตัวอย่าง visual และ layout pattern จริง