Flexbox
40 minFlexbox (Flexible Box Layout) is a modern CSS layout module designed to lay out items in a single dimension—either in a row or a column. It solves many historical layout problems, such as vertical centering and equal-height columns.
A Flexbox layout consists of a **Flex Container** (the parent) and **Flex Items** (the children). Setting `display: flex` on a container activates flex context for its direct children.
The main axis defines the direction of the items (row or column), while the cross axis runs perpendicular to it. Properties like `justify-content` align items along the main axis, and `align-items` align them along the cross axis.
Flexbox is incredibly powerful for responsive design, allowing items to grow to fill space, shrink to prevent overflow, or wrap onto new lines as needed.
Key Concepts
- One-dimensional layout (Row or Column).
- Parent is Container; Children are Items.
- Main Axis vs. Cross Axis.
- `justify-content` aligns main axis.
- `align-items` aligns cross axis.
Learning Objectives
Master
- Creating a flex container
- Controlling direction with `flex-direction`
- Aligning and distributing space
- Using `flex-grow`, `flex-shrink`, and `flex-basis`
Develop
- Solving complex alignment problems
- Building flexible, responsive components
- Understanding space distribution logic
Tips
- Use Flexbox for components and small-scale layouts (navbars, cards).
- Remember that `float` and `clear` have no effect on flex items.
- Use `flex-wrap: wrap` to allow items to break into multiple lines.
- Use `gap` to create space between flex items easily.
Common Pitfalls
- Confusing `justify-content` (main axis) with `align-items` (cross axis).
- Applying flex properties to the children instead of the container (or vice versa).
- Forgetting that Flexbox is one-dimensional (use Grid for 2D).
- Not considering content size when using `flex-grow`.
Summary
- Flexbox simplifies alignment and distribution.
- It operates on a main axis and a cross axis.
- It is ideal for UI components and 1D layouts.
- It replaces older hacks like floats and tables.
Exercise
Create a flex container that centers its children both horizontally and vertically.
.container {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
background-color: lightgray;
}
Exercise Tips
- Try changing flex-direction to column to see how axes change.
- Experiment with different justify-content values (space-between, space-around).
- Use flex-wrap: wrap to see how items behave when they overflow.
- Add gap property to create space between flex items easily.