CSS
Structuring Grid Layouts with Explicit Line Names
Utilize CSS Grid line names to precisely define grid tracks and span elements across multiple lines, enhancing readability and maintainability of complex layouts.
.line-name-grid-container {
display: grid;
grid-template-columns: [col-start] 1fr [col-middle] 1fr [col-end];
grid-template-rows: [row-start] auto [header-end] 1fr [content-end] auto [footer-end];
gap: 15px;
width: 100%;
max-width: 900px;
height: 400px;
border: 2px solid #333;
margin: 20px auto;
background-color: #f5f5f5;
}
.header {
grid-column: col-start / col-end; /* Span from col-start to col-end */
grid-row: row-start / header-end; /* Span from row-start to header-end */
background-color: #ffcccb;
padding: 15px;
text-align: center;
font-weight: bold;
}
.sidebar {
grid-column: col-start / col-middle;
grid-row: header-end / content-end;
background-color: #dcdcdc;
padding: 15px;
}
.main-content {
grid-column: col-middle / col-end;
grid-row: header-end / content-end;
background-color: #ccffcc;
padding: 15px;
}
.footer {
grid-column: col-start / col-end;
grid-row: content-end / footer-end;
background-color: #cce0ff;
padding: 15px;
text-align: center;
}
How it works: This snippet demonstrates how to use explicit line names in CSS Grid to define a layout. Instead of just numeric indices, `grid-template-columns` and `grid-template-rows` are assigned meaningful names (e.g., `[col-start]`). Grid items then use these names (e.g., `grid-column: col-start / col-end;`) to precisely place and span across tracks. This approach makes grid definitions more semantic, easier to understand for collaborators, and more robust to layout changes, as it refers to named lines rather than potentially shifting numeric indices, especially in larger, more complex designs.