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
31
One Response