CSS Grid Layout is one of the powerful and flexible tools in CSS for creating complex and organized structures on web pages. By using this tool, we can easily organize elements into rows and columns, making the website visually organized. Inside the grid, we can utilize named lines that allow us to use human-readable names instead of simple numbers to specify the start and end of elements.
Using named lines has multiple advantages. First, it makes it easier to read and understand the code when there are many lines or elements. Second, we can make changes to the grid without the need to update all numbers. Additionally, this method allows teams to work collaboratively on a project, making the code easier to understand.
Named lines in CSS Grid are defined using the 'grid-template-columns' and 'grid-template-rows' properties. In this property, we can specify the lines using [name]. For example, if we have a column named 'main-start' and 'main-end', we can easily define the elements that fall between these lines.
For working with named lines, you should first become familiar with the basic principles of Grid Layout. After that, you can comfortably use the names alongside other CSS Grid properties such as grid-gap, grid-area, etc. Let's see this concept in action with a simple example.
Example of Grid Layout with named lines
.grid-container {
display: grid;
grid-template-columns: [main-start] 1fr [main-end];
grid-template-rows: [header-start] auto [header-end main-start] 1fr [main-end footer-start] auto [footer-end];
grid-template-areas:
"header"
"main"
"footer";
}
.header {
grid-area: header;
}
.main {
grid-area: main;
}
.footer {
grid-area: footer;
}
Code Description
.grid-container
This div acts as a grid container and displays its elements in a grid format.
display: grid;
This property defines the container as a grid.
grid-template-columns
Columns are defined using the names 'main-start' and 'main-end'.
grid-template-rows
Rows are defined using different names and each row is given a specific name.
grid-template-areas
Defines the layout of the grid using names of areas like "header", "main", and "footer".
.header, .main, .footer
Each of these sections occupies a specific area in the grid container, and each area is visually represented based on its designated name.