What is Flexbox in CSS: Simple Explanation and Example
flexbox in CSS is a layout model that helps arrange items in a container, making it easy to align and distribute space among them. It works by turning the container into a flexible box that adjusts its items automatically to fit different screen sizes and directions.How It Works
Imagine you have a row of boxes on a shelf, but the shelf can stretch or shrink to fit the room. Flexbox works like that shelf, allowing the boxes (items) inside a container to grow, shrink, or wrap depending on the available space. Instead of placing items with fixed sizes, flexbox lets the container decide how to arrange them smoothly.
It works by setting the container's display to flex. This changes how the child items behave: they line up in a row or column, and you can control their alignment, spacing, and order easily. This is like having a magic shelf that rearranges itself so everything fits nicely without overlapping or leaving big gaps.
Example
This example shows a container with three colored boxes arranged in a row using flexbox. The boxes space out evenly and stay centered vertically.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flexbox Example</title> <style> .container { display: flex; justify-content: space-around; align-items: center; height: 150px; border: 2px solid #333; background-color: #f0f0f0; } .box { width: 80px; height: 80px; background-color: #4CAF50; color: white; display: flex; justify-content: center; align-items: center; font-weight: bold; border-radius: 8px; } .box:nth-child(2) { background-color: #2196F3; } .box:nth-child(3) { background-color: #FF5722; } </style> </head> <body> <div class="container"> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> </div> </body> </html>
When to Use
Use flexbox when you want to create flexible layouts that adjust smoothly to different screen sizes or content amounts. It is perfect for navigation bars, toolbars, card layouts, or any group of items that need to line up in a row or column with consistent spacing.
For example, if you want buttons to spread evenly across a header or images to wrap nicely on smaller screens, flexbox makes this easy without complicated calculations or floats.
Key Points
- Flexbox makes layout flexible and responsive by controlling item alignment and spacing.
- Set
display: flex;on a container to activate flexbox. - Use properties like
justify-contentandalign-itemsto control item placement. - Flexbox works well for one-dimensional layouts (row or column).
- It simplifies building layouts that adapt to different screen sizes.
Key Takeaways
display: flex; on the container.