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
CSS grid-area Property
The CSS grid-area property is a shorthand property that allows you to specify a grid item's placement within a grid container by setting its grid-row-start, grid-column-start, grid-row-end, and grid-column-end values in a single declaration.
Syntax
selector {
grid-area: grid-row-start / grid-column-start / grid-row-end / grid-column-end;
}
Possible Values
| Value | Description |
|---|---|
line number |
Grid line numbers (1, 2, 3, etc.) |
span n |
Span across n grid tracks |
auto |
Automatic placement (default) |
grid-area-name |
Reference to a named grid area |
Example: Grid Area with Line Numbers
The following example demonstrates how to use grid-area to position grid items using line numbers −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
background-color: #4CAF50;
grid-template-columns: auto auto auto auto;
padding: 20px;
grid-gap: 10px;
}
.container > div {
background-color: #FF9800;
text-align: center;
padding: 20px 0;
font-size: 18px;
color: white;
font-weight: bold;
}
.item1 {
grid-area: 1 / 2 / 3 / 4;
}
.item2 {
grid-area: 2 / 1 / 3 / 2;
}
</style>
</head>
<body>
<div class="container">
<div class="item1">Item 1</div>
<div class="item2">Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
</div>
</body>
</html>
A grid layout with Item 1 spanning from row 1 to 3 and column 2 to 4, Item 2 positioned at row 2 column 1, and remaining items filling available spaces automatically.
Example: Using Named Grid Areas
You can also use grid-area with named grid areas defined in grid-template-areas −
<!DOCTYPE html>
<html>
<head>
<style>
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
grid-gap: 15px;
padding: 20px;
background-color: #f0f0f0;
}
.header { grid-area: header; background-color: #2196F3; }
.sidebar { grid-area: sidebar; background-color: #9C27B0; }
.content { grid-area: content; background-color: #FF5722; }
.footer { grid-area: footer; background-color: #4CAF50; }
.layout > div {
padding: 20px;
text-align: center;
color: white;
font-weight: bold;
}
</style>
</head>
<body>
<div class="layout">
<div class="header">Header</div>
<div class="sidebar">Sidebar</div>
<div class="content">Content</div>
<div class="footer">Footer</div>
</div>
</body>
</html>
A typical website layout with header spanning the full width at top, sidebar on the left, main content area on the right, and footer spanning the full width at bottom.
Conclusion
The grid-area property provides a concise way to position grid items either by specifying grid line numbers or by referencing named grid areas. It's particularly useful for creating complex layouts with precise element positioning.
Advertisements
