How to Use align-items in CSS: Simple Guide with Examples
Use the
align-items property in CSS to control how flex items are aligned vertically inside a flex container. It works only when the container has display: flex or display: inline-flex. Common values include flex-start, center, and stretch.Syntax
The align-items property sets the default vertical alignment for all flex items inside a flex container.
align-items: flex-start;aligns items to the top.align-items: center;centers items vertically.align-items: flex-end;aligns items to the bottom.align-items: stretch;stretches items to fill the container height (default).align-items: baseline;aligns items along their text baseline.
css
.flex-container {
display: flex;
align-items: center;
}Example
This example shows a flex container with three boxes aligned vertically in the center using align-items: center;.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Align Items Example</title> <style> .container { display: flex; height: 150px; border: 2px solid #333; align-items: center; gap: 10px; } .box { width: 60px; height: 60px; background-color: #4CAF50; color: white; display: flex; justify-content: center; align-items: center; font-weight: bold; border-radius: 5px; } </style> </head> <body> <div class="container"> <div class="box">1</div> <div class="box">2</div> <div class="box">3</div> </div> </body> </html>
Output
A horizontal row of three green boxes labeled 1, 2, and 3, each vertically centered inside a tall container with a border.
Common Pitfalls
1. Forgetting to set display: flex on the container means align-items will not work.
2. Using align-items on non-flex containers has no effect.
3. Confusing align-items (vertical alignment in flex) with justify-content (horizontal alignment in row direction).
css
/* Wrong: No flex container */ .container { align-items: center; /* No effect without display:flex */ } /* Right: Flex container with align-items */ .container { display: flex; align-items: center; }
Quick Reference
| Value | Description |
|---|---|
| flex-start | Align items to the top of the container |
| center | Align items vertically centered |
| flex-end | Align items to the bottom of the container |
| stretch | Stretch items to fill container height (default) |
| baseline | Align items along their text baseline |
Key Takeaways
Use align-items inside a flex container to control vertical alignment of items.
Always set display: flex on the container for align-items to work.
Common values are flex-start, center, flex-end, stretch, and baseline.
align-items affects the cross axis (vertical in row direction).
Don’t confuse align-items with justify-content, which controls main axis alignment.