Grid Template Areas in CSS provide a powerful way to visually organize and layout grid items using named grid areas. This feature allows developers to create complex and responsive grid layouts with ease.
Grid Template Areas are defined within the 'grid-template-areas'
property of the grid container.
.container {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
}
Grid items are assigned to specific areas using the 'grid-area'
property.
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.main {
grid-area: main;
}
.footer {
grid-area: footer;
}
Adjust grid template areas based on viewport size for responsive layouts.
@media screen and (max-width: 768px) {
.container {
grid-template-areas:
"header header"
"main main"
"sidebar sidebar"
"footer footer";
}
}
Use periods ('.'
) to represent empty grid areas within the template.
.container {
grid-template-areas:
"header header header"
"sidebar . main"
"footer footer footer";
}
Besides defining grid areas, you can also name individual grid lines to create more precise layouts.
.container {
display: grid;
grid-template-columns: [col1] 100px [col2] 100px [col3] auto [col4];
grid-template-rows: [row1] 50px [row2] 50px [row3] auto [row4];
}
Grid items can span multiple rows and columns, allowing for more flexible layouts.
.main {
grid-area: main;
grid-column: col2 / col4; /* Span from column 2 to column 4 */
grid-row: row2 / span 2; /* Start at row 2 and span 2 rows */
}
Use the 'repeat()'
function to simplify grid area declarations for repetitive patterns.
.container {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
}
Grid items can also be placed in implicit grid areas outside of the defined template areas.
.container {
display: grid;
grid-template-columns: 100px 100px;
grid-auto-rows: 50px; /* Implicit rows */
}
.extra {
grid-column: 1 / span 2; /* Spanning two columns */
}
Create nested grid layouts within specific template areas.
.container {
grid-template-areas:
"header header"
"sidebar main";
}
.main {
display: grid;
grid-template-areas:
"content content"
"sidebar sidebar";
}
Grid Template Areas provide a flexible and intuitive way to organize grid layouts in CSS. By defining named areas within the grid template and assigning grid items to those areas, developers can create complex and responsive designs with ease. Happy Coding! ❤️