CSS Grid Container
Master the parent element that creates grid layouts
๐ฆ What is a Grid Container?
A grid container is the parent element that establishes a grid formatting context. When you apply
display: grid
to an element, it becomes a grid container and its direct children become grid items.
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 20px;
}
Output:
Essential Grid Container Properties
display: grid
Creates a grid container
.container {
display: grid;
}
grid-template-columns
Defines column sizes
.container {
grid-template-columns: 200px 1fr 100px;
}
grid-template-rows
Defines row sizes
.container {
grid-template-rows: 100px auto 50px;
}
gap
Sets spacing between items
.container {
gap: 20px;
}
๐น Basic Grid Container Setup
To create a simple 3-column grid container, use display: grid with grid-template-columns. Example: grid-template-columns: 1fr 1fr 1fr; or repeat(3, 1fr). Add gap: 1rem; for spacing. This establishes the grid context where child items auto-place into cells. The foundation for all grid layouts, itโs semantic, responsive-ready, and separates structure from content for maintainable code.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 15px;
padding: 20px;
background-color: #f5f5f5;
}
.grid-item {
background-color: #007acc;
color: white;
padding: 20px;
text-align: center;
border-radius: 4px;
}
Output:
๐น Responsive Grid Container
Create responsive grids using auto-fit or auto-fill with minmax(). Example: grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));. This automatically adjusts column count to fit available space, ensuring no empty tracks with auto-fit or maintaining track count with auto-fill. Produces fluid, gap-free layouts without media queries, ideal for card grids, galleries, and dynamic content.
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
.card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 8px;
text-align: center;
}
Output:
๐น Grid Container Alignment
Control grid item alignment within the container using justify-items and align-items. justify-items aligns items on the row axis (horizontal); align-items on the column axis (vertical). Values: start, end, center, stretch. Sets default alignment for all items. For individual item overrides, use justify-self and align-self. Essential for precise control in complex grid layouts.
.aligned-grid {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(2, 80px);
gap: 10px;
justify-content: center;
align-content: center;
height: 300px;
background-color: #f0f0f0;
border: 2px solid #ccc;
}