Flexbox, short for Flexible Box Layout Module, is a CSS layout model designed to make it easier to arrange elements along a single axis (row or column). It’s particularly useful for creating responsive and dynamic layouts.
Basic Concepts:
- Flex Container:
- The parent element that contains flex items.
- You apply the
display: flexproperty to it.
- Flex Items:
- The child elements within the flex container.
Key Flexbox Properties
- Flex Container Properties:
flex-direction: Controls the main-axis direction (row or column).row(default): Items are arranged horizontally.row-reverse: Items are arranged horizontally in reverse order.column: Items are arranged vertically.column-reverse: Items are arranged vertically in reverse order.
flex-wrap: Determines whether flex items wrap onto multiple lines.nowrap(default): Items don’t wrap.wrap: Items wrap onto multiple lines.wrap-reverse: Items wrap onto multiple lines, but in reverse order.
justify-content: Aligns flex items along the main axis.flex-start: Items are aligned to the start of the container.flex-end: Items are aligned to the end of the container.center: Items are centered within the container.space-between: Items are spaced evenly, with space between them.space-around: Items are spaced evenly, with space around them.space-evenly: Items are spaced evenly, with equal space between them and around them.
align-items: Aligns flex items along the cross axis.flex-start: Items are aligned to the start of the cross axis.flex-end: Items are aligned to the end of the cross axis.center: Items are centered along the cross axis.stretch(default): Items are stretched to fill the cross axis.
align-content: Aligns multiple lines of flex items along the cross axis.flex-start: Lines are aligned to the start of the cross axis.flex-end: Lines are aligned to the end of the cross axis.center: Lines are centered along the cross axis.space-between: Lines are spaced evenly, with space between them.space-around: Lines are spaced evenly, with space around them.stretch(default): Lines are stretched to fill the cross axis.
Flex Item Properties
order: Controls the order of flex items.flex-grow: Determines how much a flex item should grow relative to other flex items.flex-shrink: Determines how much a flex item should shrink relative to other flex items.flex-basis: Sets the initial size of a flex item before it grows or shrinks.align-self: Overrides thealign-itemsproperty for a specific flex item.
Example
.flex-container {
display: flex;
justify-content: space-between;
align-items: center;
}
.flex-item {
flex: 1;
border: 1px solid black;
margin: 10px;
}
This code creates a flex container with three flex items that are spaced evenly and centered vertically. Each item will grow or shrink to fill the available space.