Skip to main content

Basics of Grid Display

The display: grid; value in CSS enables the Grid Layout, a two-dimensional layout system that offers a more robust and controlled way to handle both rows and columns in your design.

Basic Concepts

  1. Grid Container: The element on which you apply display: grid; becomes the grid container.
  2. Grid Items: The immediate children of the grid container are grid items.
  3. Grid Lines: The dividing lines that make up the structure of the grid.
  4. Grid Tracks: The space between two adjacent grid lines, either horizontally (columns) or vertically (rows).
  5. Grid Cells: A single unit of the grid, defined by the intersection of a grid row and a grid column.
  6. Grid Areas: A rectangular area between four grid lines, which can contain one or more grid cells.

Syntax

To define a grid container:

.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* Three equal columns */
grid-template-rows: 100px 200px; /* Two rows of different heights */
}

Key Properties

On the Grid Container

  • grid-template-columns and grid-template-rows: Define the size of the columns and rows.
  • grid-gap: Defines the gap between grid items.
  • grid-template-areas: Defines named grid areas.

On the Grid Items

  • grid-column and grid-row: Specify where an item should be placed.
  • grid-area: Assigns an item to a named grid area.

Examples

Basic 3x2 Grid

.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 1fr);
}

Named Areas

.container {
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.footer { grid-area: footer; }

Best Practices

  1. Semantic Structure: Use Grid to enhance the semantic structure of your HTML, not to break it.
  2. Fallbacks: Provide fallback layouts for browsers that don't support CSS Grid.
  3. Responsive Design: Use media queries in conjunction with Grid layout to create fully responsive designs.
  4. Debugging: Modern browsers have excellent dev tools for debugging Grid layouts.

Browser Support

CSS Grid is well-supported in modern browsers, but it's always a good idea to check compatibility if you need to support older versions.