What Is Flexbox?
Flexbox is a modern CSS layout system that makes it easy to center, align, and arrange elements. It’s way simpler than using floats or tables.
Basic Flexbox Container
To use Flexbox, you must activate it on a container:
.container {
display: flex;
}
Horizontal Alignment
.container {
display: flex;
justify-content: center; /* left, right, space-between, etc. */
}
Vertical Alignment
.container {
display: flex;
align-items: center; /* top, center, bottom */
}
Putting It Together
.container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
background: #222;
}
This centers everything inside the container both horizontally and vertically.
Flex Direction
By default, items go left → right. To stack them vertically:
.container {
display: flex;
flex-direction: column;
}
Spacing Items
.container {
display: flex;
justify-content: space-between;
}
Gap Between Items
Easier than using margin:
.container {
display: flex;
gap: 20px;
}
Example — A Simple Card Layout
<div class="cards">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
</div>
<style>
.cards {
display: flex;
gap: 20px;
}
.card {
background: #333;
padding: 20px;
border-radius: 6px;
flex: 1;
}
</style>
Why Flexbox?
- Simple alignment
- Responsive by default
- Much cleaner than floats
- Perfect for modern UI layouts
What’s Next?
Next you’ll learn about Batch loops and conditions — two essential tools for powerful scripting.