Advance CSS Layout with Flexbox (original) (raw)
Last Updated : 11 Jul, 2025
Flexbox is a powerful CSS layout model that simplifies the creation of flexible and responsive layouts. It allows you to align and distribute space among items within a container, making complex designs easier to manage.
Flexbox is particularly useful for building responsive designs that adapt seamlessly to different screen sizes.
Layout Modes Before Flexbox
Before the introduction of Flexbox, CSS relied on four primary layout modes:
- **Block Layout: Used for structuring sections of a webpage (e.g.,
<div>,<p>). - **Inline Layout: Used for text and inline elements (e.g.,
<span>,<a>). - **Table Layout: Used for displaying tabular data in a two-dimensional grid (e.g.,
<table>,<tr>). - **Positioned Layout: Used for explicitly positioning elements (e.g.,
position: absolute,position: relative).
Why Use Flexbox?
Flexbox simplifies creating responsive, flexible layouts by aligning and spacing elements dynamically, reducing the need for complex CSS or extra markup.
- **Responsive Design: Adapts layouts seamlessly to different screen sizes.
- **Ease of Use: Simplifies alignment and spacing with minimal code.
- **Dynamic Sizing: Automatically adjusts item sizes to fit available space.
- **Efficient Layouts: Perfect for modern, clean, and maintainable designs.
**Flex Properties
Here is a list of the main CSS Flexbox properties:
- flex-direction
- flex-wrap
- flex-flow
- justify-content
- align-items
- align-content
**1. flex-direction
The flex-direction is used to define the direction of a flexible item. The default axis is horizontal in Flexbox, so the items flow into a row.
html `
`
- **flex-wrap: wrap: Ensures items move to the next line when they exceed the container's width.
- .**item styling: Each box has a fixed size and centers text for a clean layout.
**4. justify-content
The justify-content property is used to align the flex items according to the main axis within a flexbox container.
html `
`
- **justify-content: center: Centers the items horizontally within the container.
- .**item styling: Each item is styled to maintain size and alignment for clarity.
**5. align-items
CSS align-items property is used to align flex items vertically according to the cross axis.
html `
`
- **align-content: space-between: Distributes the lines evenly with space in between.
- .item styling: Provides a visual understanding of how items align across multiple lines.
Best Practices for Advanced CSS Layouts with Flexbox:
- Use display: flex to create flexible containers.
- Apply flex-direction to set the main axis direction.
- Utilize **justify-content to align items along the main axis.