Flexbox Layout Fundamentals and Implementation

Implementing Flexbox Layout

To enable flexbox layout, set the display property on the parenet HTML element:

display: flex;

Alternatively, you can use inline flex display:

display: inline-flex;

When either display: flex or display: inline-flex is applied to a container, all its direct children automatically become flex items.

The element using flex layout is called a flex container, while its direct children are referred to as flex items.

Flex Container Properties

Flex Item Properties

flex-basis

flex-basis: length|auto|initial|inherit;

length: A length unit or percentage specifying the initial size of the flex item.

auto: Default value. Size equals the item's content size. If no size is specified, it's deetrmined by content.

flex-shrink Calculation Formula

item-shrink: (item-width × shrink-ratio) ÷ (sum of all item-width × shrink-ratio) × available-negative-space

Example:

flex: 0 2 300px;

flex: 0 1 200px;

flex: 0 2 100px;

Total required space: 300 + 200 + 100 = 600px

Container width: 400px

Negative space to distribute: 200px

Shrink ratios: 2, 1, 2

Total Weight (TW) = sum of (width × shrink-factor):

2 × 300 = 600

1 × 200 = 200

2 × 100 = 200

TW = 600 + 200 + 200 = 1000

Each item's shrink amount: (width × shrink-factor) ÷ TW × negative-space

First item: (300 × 2) ÷ 1000 × 200 = 120px

Second item: (200 × 1) ÷ 1000 × 200 = 40px

Third item: (100 × 2) ÷ 1000 × 200 = 40px

Final widths: 300-120=180px, 200-40=160px, 100-40=60px

Practical Tips

In flex layouts, margin: auto consumes available space in each direction. Setting appropriate margins can achieve specific effects. For example, applying margin-left: auto to a flex item will push it to the right edge, effective consuming all available space on that side.

Tags: css Flexbox flex-container flex-items flex-shrink

Posted on Sat, 16 May 2026 15:30:43 +0000 by danc81