Skip to main content

Grid Tracks

The concept of "grid-tracks" is central to mastering CSS Grid, as it forms the building blocks of your grid layout.

What are Grid Tracks?

Grid tracks are the spaces between two adjacent grid lines, either horizontally (forming rows) or vertically (forming columns). They serve as the containers in which your grid items will be placed.

Defining Grid Tracks

You define grid tracks using the grid-template-columns and grid-template-rows properties on the grid container. The values you provide for these properties determine the size of the tracks.

/* Defining grid tracks */
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* 3 column tracks */
grid-template-rows: 100px 200px; /* 2 row tracks */
}

In this example, the grid container will have 3 column tracks and 2 row tracks. The column tracks will have sizes relative to each other (1:2:1), and the row tracks will have fixed sizes of 100px and 200px.

Sizing Grid Tracks

You can size grid tracks using various units:

  • Fixed Units: Such as px, em, rem.
  • Percentage: Relative to the grid container.
  • Fractional Units (fr): Represents a fraction of the available space.
  • Auto: Sizes the track based on its content.
  • Min-content / Max-content: Sizes the track to the minimum or maximum content size.

Dynamic Sizing with Functions

You can also use functions like repeat(), minmax(), and auto-fill for more dynamic sizing.

/* Using functions */
.grid-container {
grid-template-columns: repeat(3, 1fr);
grid-template-rows: minmax(100px, auto);
}

Named Grid Tracks

For better readability and maintainability, you can name your grid tracks.

.grid-container {
grid-template-columns: [start] 1fr [middle] 2fr [end];
grid-template-rows: [row1-start] 100px [row1-end] 200px [row2-end];
}

Key Takeaways

  1. Flexibility: Grid tracks offer a high level of flexibility for complex layouts.
  2. Responsiveness: Using relative units and functions, you can easily make your grid responsive.
  3. Control: You have precise control over the size, placement, and alignment of items within grid tracks.