CSS Flexbox
Flexbox lays out items in a single row or column and distributes the available space between them.
Set <code>display: flex</code> on a container and its direct children become flex items that you can align, space, and reorder. Flexbox is the go-to tool for one-dimensional layouts such as toolbars, button groups, and rows of cards.
Creating A Flex Container
A simple row with gaps
<!DOCTYPE html>
<html>
<head>
<style>
.row {
display: flex;
gap: 16px;
}
</style>
</head>
<body>
<div class="row">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
</div>
</body>
</html>The Two Axes
Items flow along the main axis, and <code>flex-direction</code> decides whether that axis runs horizontally or vertically. The cross axis is always perpendicular to it, which is why alignment uses two different properties.
Centering In Both Directions
Perfect centering
<!DOCTYPE html>
<html>
<head>
<style>
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 200px;
}
</style>
</head>
<body>
<div class="center">
<p>Centered text</p>
</div>
</body>
</html>Flexible And Wrapping Items
Cards that grow and wrap
<!DOCTYPE html>
<html>
<head>
<style>
.cards {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 200px;
}
</style>
</head>
<body>
<div class="cards">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</div>
</body>
</html>The shorthand <code>flex: 1 1 200px</code> lets each card grow and shrink from a 200px base, so a row fills the space and extra cards wrap onto the next line. For grids in two dimensions, reach for CSS Grid instead.
Exercise: CSS Flexbox
By default, with no flex-direction set, along which axis do flex items align?