grid-template
Defintion
The grid-template property is a shorthand property used in CSS Grid Layout to define both the rows and columns of a grid, as well as any grid gaps, in a single declaration.
Examples
Basic usage:
.grid-container {
display: grid;
grid-template: 100px 100px 100px / 100px 100px 100px;
}
Using the repeat() function:
.grid-container {
display: grid;
grid-template: repeat(3, 1fr) / repeat(3, 100px);
}
Specifying grid gaps:
.grid-container {
display: grid;
grid-template: 100px 1fr 2fr / 100px 1fr 2fr;
grid-gap: 10px;
}
Values
Value | Description |
---|---|
<grid-template-rows> / <grid-template-columns> | Specifies the rows and columns of the grid, separated by a slash (/). Each row and column can be a length, a percentage, or the fr unit. |
none | Specifies that the grid has no explicit rows or columns, and will automatically create them as needed. |
subgrid | Specifies that the grid should inherit its rows and columns from its parent grid. |
<grid-template-areas> | Specifies the placement of grid items using named grid areas. |
Best Practices
- Use named grid areas whenever possible, as they make your code more readable and easier to maintain.
- Use fr units to create flexible, responsive grids that adjust to the size of the container.
- Use the repeat() function to create repeated patterns of rows and columns, which can save time and make your code more concise.
- Consider using the minmax() function to create rows and columns that have a minimum and maximum size, ensuring that they don't get too small or too large.
- Use the grid-gap property to add space between grid items, improving readability and making the layout more visually appealing.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | No | Yes | Yes |