Module 3: Advanced CSS Techniques
Day 13: Grid - Basics and Practical Use
Introduction to CSS Grid
CSS Grid Layout is a powerful layout system designed for two-dimensional layouts. It allows you to create complex layouts easily and consistently across different screen sizes.
Basic Concepts
The primary concepts in CSS Grid are the grid container and the grid items. The container is set to use the grid layout, and the items inside it are the grid items.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Defines three equal columns */
grid-gap: 10px; /* Defines the gap between the grid items */
}
.item {
background-color: #0056b3;
color: white;
padding: 20px;
text-align: center;
border-radius: 8px;
}
Grid Container Properties
Here are some important properties for the grid container:
.container {
display: grid;
grid-template-columns: 1fr 2fr; /* Defines columns */
grid-template-rows: 100px auto; /* Defines rows */
grid-gap: 10px; /* Defines the gap between items */
justify-items: stretch; /* Aligns items horizontally */
align-items: stretch; /* Aligns items vertically */
}
Grid Item Properties
Here are some important properties for the grid items:
.item {
grid-column: 1 / 3; /* Span two columns */
grid-row: 1; /* Place in the first row */
justify-self: center; /* Align horizontally */
align-self: center; /* Align vertically */
}
Practical Example
Let's see a practical example of using CSS Grid to create a simple layout:
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
</div>
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
}
.item {
background-color: #0056b3;
color: white;
padding: 20px;
text-align: center;
border-radius: 8px;
}
Example Output:
Item 1
Item 2
Item 3
Item 4
Item 5
Item 6