Building Layouts with Flexbox
Flexbox makes it easy to distribute space and align items within a container. Use display: flex;
on a parent and flex properties on children to control direction, wrapping, alignment and spacing.
/* Flex container */
.container {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
/* Flex items */
.item {
flex: 1 1 200px; /* grow, shrink, base width */
}
/* Alignment */
.container {
justify-content: center; /* start, center, space-between */
align-items: stretch; /* start, center, stretch */
}
Key Flexbox Properties
- display: flex; — defines a flex container.
- flex-direction — row, column, and their reverse.
- justify-content — horizontal alignment within container.
- align-items — vertical alignment of items.
- flex-wrap — allow items to wrap onto new lines.
Creating Grids with CSS Grid
CSS Grid enables two-dimensional control over rows and columns. Define tracks with grid-template-columns
and grid-template-rows
, then place items using line numbers or grid areas.
/* Grid container */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
grid-auto-rows: auto;
gap: 1rem;
}
/* Place item in grid area */
.header {
grid-column: 1 / -1; /* spans all columns */
}
.content {
grid-column: 1 / 3;
grid-row: 2;
}
Key Grid Properties
- display: grid; — defines a grid container.
- grid-template-columns/rows — set column and row sizes.
- gap — space between grid tracks.
- grid-column/grid-row — position items by line numbers.
- auto-fit/auto-fill — responsive track repetition.