Back to Home

Flexbox Theory

Learn the core concepts and properties of CSS Flexbox layout.

Introduction to Flexbox

CSS Flexbox (Flexible Box Module) is a powerful layout model designed for one-dimensional arrangements of items. It allows developers to create dynamic and responsive layouts effortlessly, handling varying sizes and distributions of elements.

Unlike traditional layout techniques such as floats or positioning, Flexbox enables direct control over alignment, order, and spacing. With Flexbox, items can be easily centered, resized proportionally, and adapted to different screen sizes without extra media queries.

Flexbox has two main components:

Flex container: A Flex container is an element with display: flex applied, making it the parent of flex items. It controls the overall layout and arrangement of its children using properties like flex-direction, justify-content, and align-items. This powerful structure allows elements to adjust dynamically, making responsive designs much simpler.

Flex items: Flex items are the direct children of a Flex container and inherit its flexible behavior. These items can be individually controlled using properties like flex-grow, flex-shrink, and order. They can automatically resize and reposition based on their container’s rules, creating adaptable and visually balanced layouts without extra code or media queries.

Why Use Flexbox?

  • Simplifies complex layouts - Flexbox makes many layout tasks easier, like vertical centering, equal-height columns, and space distribution.
  • Responsive design - Flexbox helps create layouts that adapt to different screen sizes without using media queries.
  • Direction-agnostic - Unlike traditional methods, Flexbox works well regardless of text direction or writing mode.
  • Space distribution - Easily control how extra space is distributed or how items shrink when there's not enough space.
  • Alignment control - Precisely control alignment along both axes.

Basic Terminology

Flex Container

The parent element that has display: flex or display: inline-flex applied to it.

.container {
  display: flex;
}

Flex Items

The direct children of a flex container automatically become flex items.

Item 1
Item 2
Item 3

Difference Between flex and inline-flex

PropertyDescription
display: flexThe element behaves as a block-level flex container, spanning the full width available.
display: inline-flexThe element remains inline, aligning within surrounding inline elements while acting as a flex container.

Axes in Flexbox

Flexbox operates on two axes: the main axes and the cross axes.

Main Axes

Defined by the flex-direction property. It can be horizontal (row) or vertical (column).

  • justify-content aligns items along the main axes

Cross Axes

Perpendicular to the main axes. If the main axes is horizontal, the cross axes is vertical, and vice versa.

  • align-items aligns items along the cross axes