9. Flexbox
Source: Dev.to
BootCamp by Dr. Angela
Display: Flex
/* example */
.container {
display: flex;
gap: 10px;
}
- When
display: flexis applied, all child elements are laid out in a single row by default. - The flex layout ignores traditional display types (
inline,block,inline‑block,none) for child elements.
inline-flex
- Behaves similarly to
inline-block. - The container itself behaves like an inline element (e.g., “).
- Its width adjusts to fit its content (based on the largest child item).
- Flex rules still apply to its children.
Flex Direction
-
flex-directiondetermines the main axis and cross axis.row(default): main axis →, cross axis ↓column: main axis ↓, cross axis →row-reverse/column-reverse: reverse the start/end order along the main axis
-
flex-basis- Defines the initial size of an individual flex item along the main axis.
- Applied to flex items only, not the flex container.
- Acts like
widthin row direction andheightin column direction.
Flex Layout
order: 0;(default) applies to flex items; higher values appear later along the main axis (to the right in a row).
Wrapping (flex-wrap – container)
nowrap(default): all items stay on one line.wrap: items wrap onto multiple lines.wrap-reverse: items wrap in the opposite direction.
Main‑axis alignment (justify-content)
flex-start | flex-end | center | space-between | space-around | space-evenly
Cross‑axis alignment (single line – align-items)
flex-start | flex-end | center | baseline | stretch
Requires a defined container height (e.g., height: 70vh). Works when items are not wrapped.
Individual item alignment (align-self)
Overrides align-items for a single flex item; uses the same values.
Cross‑axis alignment for multiple lines (align-content)
flex-start | flex-end | center | space-between | space-around | space-evenly | stretch
Requires flex-wrap: wrap; and controls spacing between rows or columns.
Shorthand (flex-flow)
/* example */
flex-flow: row wrap; /* equivalent to flex-direction: row; flex-wrap: wrap; */
Flex Sizing
Sizing priority (low → high):
Content size → width → flex-basis → min-width / max-width
Content‑based sizes
min-content: size based on the longest word (minimum possible width).max-content: size based on all content on one line (maximum possible width).
Flex Grow / Shrink
flex-grow: controls how much an item grows when extra space is available.flex-shrink: controls how much an item shrinks when space is limited.0: no growing or shrinking.
Flex shorthand
/* example */
flex: 1 1 0; /* flex-grow: 1; flex-shrink: 1; flex-basis: 0; */
Space is distributed proportionally based on the grow/shrink values.