🌱BeginnerCSS Flexbox
Flexbox Alignment and Flex Items
Master flex item properties: flex-grow, flex-shrink, flex-basis, align-self, and order.
Overview
Beyond the container properties, Flexbox has a set of properties you apply to individual flex items to control how they grow, shrink, and align independently.
**Item properties:**
- `flex-grow` how much the item grows to fill extra space (0 = no grow)
- `flex-shrink` how much the item shrinks when space is tight (0 = no shrink)
- `flex-basis` the starting size before grow/shrink is applied
- `flex` shorthand: grow shrink basis (e.g., `flex: 1` = grow to fill equally)
- `align-self` overrides align-items for a single item
- `order` changes visual order without changing DOM order
The `flex` shorthand with a single number (like `flex: 1`) is the most common it means the item can grow to fill available space proportionally.
Key Points
- •flex: 1 on all items makes them share space equally
- •flex-grow: 0 prevents an item from growing beyond its content size
- •flex-basis: 0 means start from nothing and distribute space purely by flex-grow
- •align-self: overrides the container's align-items for one specific item
- •order: 2 puts an item after order: 1 items default order is 0
- •flex: 1 1 auto = grow, shrink, use content size as basis
Examples
Proportional growth with flex
.sidebar { flex: 1; } /* 1/4 of space */
.main { flex: 3; } /* 3/4 of space */
/* flex: 3 gets 3x more space than flex: 1 */flex: 1 on both items means equal sharing. flex: 3 gets 3x the space of flex: 1.
Fixed sidebar + flexible main
.layout {
display: flex;
gap: 24px;
}
.sidebar {
flex: 0 0 260px; /* no grow, no shrink, always 260px */
}
.main {
flex: 1; /* grows to fill remaining space */
}"flex: 0 0 260px" = do not grow, do not shrink, always 260px wide.
align-self and order
.flex-container {
display: flex;
align-items: flex-start; /* all items at top */
}
.tall-item {
align-self: stretch; /* this one stretches to full height */
}
/* Reorder visually without changing HTML */
.first { order: 1; }
.second { order: 2; }
.third { order: 3; }Common Mistakes
- Confusing flex: 1 (grow to fill) with flex-basis: 1px (starting size)
- Using order to reorganize navigation visually this breaks keyboard and screen reader order
- Setting flex-grow without flex-basis the item starts from its content size, which can be uneven
Note
For a sidebar + main layout: ".sidebar { flex: 0 0 250px; } .main { flex: 1; }" inside a flex container is the cleanest and most reliable approach.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4