Letโs dive into one of the most powerful tools in modern CSS โ Flexbox!
๐ LESSON 8: Flexbox โ Modern Layout Made Easy
โ Learning Goals:
- Understand what Flexbox is and why it’s useful
- Learn the most important Flexbox properties
- Create flexible layouts with just a few lines of code
- Build a responsive card layout using Flexbox
๐งพ Lesson Content (Text for Website)
๐ What is Flexbox?
Flexbox (Flexible Box Layout) is a CSS module that makes it easy to design layouts that adapt to screen size and content.
No more float
, margin-hack
, or display: table
tricks. Flexbox handles it all beautifully!
๐งฑ The Flexbox Parent
To activate Flexbox, apply this to a container:
display: flex;
Thatโs it! All children (items) now become flex items.
๐ก Example:
<style>
.container {
display: flex;
}
.box {
background: #ff6f00;
color: white;
padding: 20px;
margin: 10px;
flex: 1;
}
</style>
<div class="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
Each box gets equal width, thanks to flex: 1
.
๐ Important Flexbox Properties
๐น On Parent (.container
):
Property | What it does |
---|---|
display: flex | Activates Flexbox |
flex-direction | Row (default) or column layout |
justify-content | Aligns items horizontally (main axis) |
align-items | Aligns items vertically (cross axis) |
gap | Adds spacing between items |
flex-wrap | Allows wrapping onto next line |
๐น On Children (.box
):
Property | What it does |
---|---|
flex | Controls item growth/shrink/basis |
align-self | Overrides vertical alignment |
order | Controls the order of items |
๐งช Flexbox in Action: Horizontal Menu
<style>
.nav {
display: flex;
justify-content: space-between;
background: #333;
padding: 10px;
}
.nav a {
color: white;
text-decoration: none;
padding: 10px;
}
</style>
<div class="nav">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</div>
๐ Flex Direction Column
.container {
display: flex;
flex-direction: column;
}
Stacks items vertically instead of in a row.
๐ฏ Common Layouts You Can Make with Flexbox:
- Navigation bars
- Cards in a grid
- Equal-height columns
- Centering content (vertically and horizontally!)
.center-box {
display: flex;
justify-content: center;
align-items: center;
}
๐ช Practice Task
โ Build a 3-card layout that:
- Is responsive (cards shrink on small screens)
- Uses
gap
,flex-wrap
, andjustify-content
- Centers content inside each card
๐ Quick Summary
- Flexbox is a layout system that adapts to content
- Use
display: flex
to start - Combine
justify-content
,align-items
, andflex
for full control - Super useful for responsive designs
๐ Next Lesson:
๐ Lesson 9: Responsive Design & Media Queries
19
One Response