Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Set the name to Grid Items with CSS
To set names to grid items in CSS, use the grid-area property in combination with the grid-template-areas property. This allows you to assign meaningful names to grid items and position them within named grid areas.
Syntax
/* Define named areas in the grid container */
.container {
display: grid;
grid-template-areas: "area-name1 area-name2"
"area-name3 area-name4";
}
/* Assign grid items to named areas */
.item {
grid-area: area-name;
}
Example
The following example demonstrates how to name grid items and position them using grid-area and grid-template-areas −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
background-color: #2ecc71;
grid-template-areas: 'header header header'
'sidebar main main'
'footer footer footer';
padding: 20px;
gap: 10px;
max-width: 600px;
}
.container > div {
background-color: #f39c12;
text-align: center;
padding: 20px;
font-size: 16px;
color: white;
border-radius: 5px;
}
.header {
grid-area: header;
background-color: #3498db;
}
.sidebar {
grid-area: sidebar;
background-color: #e74c3c;
}
.main {
grid-area: main;
background-color: #9b59b6;
}
.footer {
grid-area: footer;
background-color: #34495e;
}
</style>
</head>
<body>
<div class="container">
<div class="header">Header</div>
<div class="sidebar">Sidebar</div>
<div class="main">Main Content</div>
<div class="footer">Footer</div>
</div>
</body>
</html>
The output of the above code is −
A grid layout appears with: - Blue "Header" spanning the top row - Red "Sidebar" in the left column of the second row - Purple "Main Content" spanning two columns in the second row - Dark gray "Footer" spanning the bottom row All items are positioned according to their named grid areas.
Conclusion
The grid-area property combined with grid-template-areas provides a semantic way to name and position grid items. This approach makes CSS grid layouts more readable and maintainable by using descriptive area names instead of line numbers.
Advertisements
