CSS Flexbox Layout
Flexbox (Flexible Box Layout Model) is a powerful one-dimensional layout model introduced in CSS3. It's designed to provide a more efficient way to align, distribute, and order items within a container, even when their sizes are unknown or dynamic.
Flexbox is the cornerstone of modern CSS layout, perfect for building component-level layouts like navigation bars, cards, forms, etc.
Core Concepts of Flexbox
To use Flexbox, you first need a Flex Container and some Flex Items.
- Flex Container: Created by setting
display: flex;ordisplay: inline-flex;on an element. - Flex Items: All direct child elements of a flex container automatically become flex items.
Flexbox layout has two axes:
- Main Axis: Flex items are arranged along the main axis. By default, it's horizontal (left to right).
- Cross Axis: The axis perpendicular to the main axis. By default, it's vertical (top to bottom).
Flex Container Properties (Properties for Parent)
These properties are set on the flex container to control the overall layout of all items within it.
display
Defines a flex container.
flex: Creates a block-level flex container.inline-flex: Creates an inline-level flex container.
flex-direction
Sets the direction of the main axis, determining the arrangement direction of flex items.
row: (Default) Arranges horizontally from left to right.row-reverse: Arranges horizontally from right to left.column: Arranges vertically from top to bottom.column-reverse: Arranges vertically from bottom to top.
flex-wrap
Controls whether items wrap to the next line when they can't fit on one line.
nowrap: (Default) No wrapping, items shrink to fit the container.wrap: Wraps from top to bottom.wrap-reverse: Wraps from bottom to top.
justify-content
Defines how items are aligned on the main axis.
flex-start: (Default) Aligns towards the main axis start.flex-end: Aligns towards the main axis end.