Grid Layout in CSS - johnverz22/webdev1-lessons GitHub Wiki
- Introduction to CSS Grid
- Basic Grid Properties
- Step-by-Step Practice
- Common Use Cases
- CSS Grid vs. Flexbox
- Practical Example
CSS Grid is a powerful layout system that allows for two-dimensional (rows and columns) design. It provides greater flexibility than Flexbox when dealing with complex layouts.
Property | Description |
---|---|
display: grid; |
Enables grid layout on an element |
grid-template-columns |
Defines the number and size of columns |
grid-template-rows |
Defines the number and size of rows |
grid-gap or gap
|
Adds spacing between grid items |
grid-column |
Specifies how many columns an item spans |
grid-row |
Specifies how many rows an item spans |
justify-items |
Aligns items horizontally (start , center , end , stretch ) |
align-items |
Aligns items vertically (start , center , end , stretch ) |
justify-content |
Aligns the entire grid horizontally |
align-content |
Aligns the entire grid vertically |
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
</div>
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 10px;
background: #f4f4f4;
padding: 10px;
}
.grid-item {
background: steelblue;
color: white;
display: flex;
justify-content: center;
align-items: center;
height: 100px;
}
.grid-container {
grid-template-columns: 100px 1fr 2fr;
}
.grid-item:nth-child(1) {
grid-column: span 2;
}
- Dashboard Layouts
- Photo Galleries
- Product Listings
- Responsive Web Design
- Complex UI Grids
Feature | CSS Grid | Flexbox |
---|---|---|
Layout Type | Two-dimensional (rows & columns) | One-dimensional (row OR column) |
Alignment | Can align both rows and columns at once | Aligns items along a single axis |
Content Size Adaptation | Best for structured, grid-based layouts | Best for dynamically adjusting items |
Positioning | Can place items anywhere in the grid | Items adjust based on content flow |
Example Use Case | Dashboards, galleries, forms | Navigation bars, flexible lists, cards |
- Use Grid when creating structured layouts that need both rows and columns.
- Use Flexbox for single-row or single-column layouts, like navigation bars and lists.
- Combine Both when necessary—use Grid for the main layout and Flexbox inside grid items for finer control.
A simple responsive grid layout:
<div class="photo-gallery">
<img src="https://via.placeholder.com/150" alt="Sample Image">
<img src="https://via.placeholder.com/150" alt="Sample Image">
<img src="https://via.placeholder.com/150" alt="Sample Image">
</div>
.photo-gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 10px;
}
.photo-gallery img {
width: 100%;
height: auto;
}
This ensures a flexible, responsive gallery that adapts to screen size.