June 3, 2024
Introduction to CSS Grid
The CSS Grid layout model is a powerful tool for creating complex and responsive web layouts. Grid allows you to define both rows and columns, making it easy to design web pages without the need for floats or positioning.
Grid Container and Grid Items
A Grid layout consists of a grid container and its grid items. The grid container is the parent element, and the grid items are its children. To create a grid container, you use the display: grid;
property on the parent element.
Example:
.container {
display: grid;
}
Defining Grid Areas, Tracks, and Gaps
CSS Grid provides several properties to control the layout of grid items:
.container {
grid-template-columns: repeat(3, 1fr); /* Creates three equal columns */
}
.container {
grid-template-rows: 100px 200px; /* Creates two rows, the first is 100px tall, the second is 200px tall */
}
.container {
grid-gap: 10px; /* Sets a 10px gap between all grid items */
}
.container {
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
}
.item1 { grid-area: header; }
.item2 { grid-area: sidebar; }
.item3 { grid-area: content; }
.item4 { grid-area: footer; }
Advanced Grid Techniques
CSS Grid also provides properties for individual grid items:
.item {
grid-column: 1 / 3; /* Spans from column line 1 to column line 3 */
}
.item {
grid-row: 1 / 2; /* Spans from row line 1 to row line 2 */
}
.item {
justify-self: center; /* start, end, center, stretch */
}
.item {
align-self: center; /* start, end, center, stretch */
}
Exercise: Designing a Complex Webpage Layout with Grid
Let's create a complex webpage layout using CSS Grid properties.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid Layout</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="item item1">Header</div>
<div class="item item2">Sidebar</div>
<div class="item item3">Content</div>
<div class="item item4">Footer</div>
</div>
</body>
</html>
body {
margin: 0;
font-family: Arial, sans-serif;
}
.container {
display: grid;
grid-template-columns: 1fr 2fr;
grid-template-rows: 100px 1fr 50px;
grid-template-areas:
"header header"
"sidebar content"
"footer footer";
height: 100vh;
grid-gap: 10px;
}
.item {
background-color: #333;
color: white;
padding: 20px;
}
.item1 { grid-area: header; }
.item2 { grid-area: sidebar; }
.item3 { grid-area: content; }
.item4 { grid-area: footer; }
Open the HTML file in a browser to see your complex Grid layout. Experiment with different Grid properties to see how they affect the layout and behavior of your items.
Coming Up Next
In Chapter 9, we'll explore responsive design techniques, including media queries and responsive units, to create web pages that look great on all devices.
Please Sign In to post a comment.