Introduction
In the previous article, we discussed how to use grid-template-areas to design the layout you want. Today, we’ll continue by diving into additional CSS Grid properties. Let’s begin!
grid-template
grid-template is a shorthand for the grid-template-rows, grid-template-columns, and grid-template-areas properties in CSS Grid.
Its syntax is as follows:
.container {
grid-template: none;
}
.container {
grid-template: <grid-template-rows> / <grid-template-columns>;
}
The value none sets all three CSS properties—grid-template-rows, grid-template-columns, and grid-template-areas—to their default initial values.
In the previous example, James came up with an excellent layout. By using grid-template, the code can be simplified to the following:
.container {
grid-template:
"hotel hotel hotel" 1fr
"restaurant apartment apartment" 1fr
"restaurant apartment apartment" 1fr
"church church church" 1fr
/1fr 1fr 1fr;
}
The result is as follows:
grid or grid-template
I will introduce the grid property later. You can think of it as a shorthand property, which overlaps with grid-template. So, which one should you use?
In most cases, it’s better to use grid instead of grid-template since grid-template doesn’t reset certain implicit properties, such as grid-auto-columns, grid-auto-rows, and grid-auto-flow.
for example:
.container {
display: grid;
grid-template: "a b" 100px
"c d" 100px;
grid-auto-rows: 50px;
}
- grid-template defines an explicit 2x2 grid, with each row having a height of 100px.
- Even though the explicit grid already defines rows and columns, if elements overflow the explicit grid (e.g., placed in the third row or third column), new rows will be created based on grid-auto-rows with a height of 50px.
Thus, grid-template defines only the explicit grid, but it does not automatically override properties related to the implicit grid. If you use implicit grid properties (such as grid-auto-columns or grid-auto-rows) to extend the grid layout without considering their default values, it may result in unexpected layout behavior.
However, grid is a shorthand property that encompasses both explicit and implicit grid definitions, allowing for unified management of the grid layout. Using it provides a clearer way to override default values, helping to avoid omissions or inconsistencies.
So the conclusion is:
- Use grid-template when you only need to set explicit grid row and column definitions, without dealing with additional control over implicit grids.
- Use grid when you need to manage both explicit and implicit grid layout configurations, or need more complex control over automatically generated grid behavior.
Ok, See you in next blog!