CSS
Align Content Vertically and Horizontally Within CSS Grid Cells
Achieve precise internal alignment for elements inside individual CSS Grid cells by leveraging Flexbox, enabling complex and organized sub-layouts.
/* HTML */
<div class="grid-wrapper">
<div class="grid-cell">
<div class="cell-content">Top-Left</div>
</div>
<div class="grid-cell flex-center">
<div class="cell-content">Centered</div>
</div>
<div class="grid-cell flex-bottom-right">
<div class="cell-content">Bottom-Right</div>
</div>
<div class="grid-cell flex-stretch">
<div class="cell-content">Stretched</div>
</div>
</div>
/* CSS */
.grid-wrapper {
display: grid;
grid-template-columns: repeat(2, 1fr); /* 2 columns */
grid-template-rows: repeat(2, 150px); /* 2 rows, fixed height */
gap: 10px;
width: 500px; /* Example width */
height: 350px;
border: 2px solid #007bff;
font-family: sans-serif;
}
.grid-cell {
background-color: #e0f2ff;
border: 1px dashed #007bff;
display: flex; /* Make the grid cell a flex container */
padding: 5px;
}
.cell-content {
background-color: #a7d9ff;
padding: 10px;
border: 1px solid #0056b3;
}
/* Specific alignment examples */
.flex-center {
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
}
.flex-bottom-right {
justify-content: flex-end; /* Horizontally to the end */
align-items: flex-end; /* Vertically to the end */
}
.flex-stretch .cell-content {
flex-grow: 1; /* Content stretches to fill available space */
}
How it works: This snippet demonstrates a powerful technique where a CSS Grid cell is itself a Flexbox container, allowing for sophisticated alignment of content within each individual grid cell. By applying `display: flex` to a `.grid-cell` element, you can then use Flexbox properties like `justify-content` and `align-items` to precisely position its children (e.g., `.cell-content`). This pattern is incredibly useful for creating complex dashboards or layouts where each section (grid cell) requires specific internal content arrangement, combining the macro-layout power of Grid with the micro-alignment capabilities of Flexbox.