51. Introduction to Flexbox (Flexible Box Layout)
Flexbox is a one-dimensional layout system designed for distributing space among items in a single row or column. It solved nearly all the alignment and centering headaches of older CSS methods.
The Flexbox Model
Flexbox involves two main components:
- Flex Container: The parent element where
display: flex;is applied. - Flex Items: The direct children of the Flex Container.
When you set display: flex; on a container, two axes are established:
- Main Axis: The primary direction items are laid out (default is horizontal).
- Cross Axis: The axis perpendicular to the main axis (default is vertical).
Getting Started
To activate Flexbox, simply apply the display property to the parent element:
html
css .flex-container { display: flex; /* Default layout: Items go horizontally (Main Axis) */ }
.item { padding: 20px; border: 1px solid black; } /* Result: All items sit side-by-side on one line */
Key Benefit: Flexbox automatically manages the size and position of the items to fill the available space, making alignment (especially vertical centering) effortless.