CSS Flexbox Introduction

Subject: css

CSS Flexbox Introduction

CSS Flexbox (Flexible Box Layout) is a layout module that makes it easier to build responsive and dynamic layouts. It provides an efficient way to align and distribute space among items in a container, even when their sizes are unknown or change dynamically.


Why Use Flexbox?

  • Align items both horizontally and vertically with ease
  • Create responsive layouts without floats or complex positioning
  • Control spacing, wrapping, and distribution of elements
  • Handle content that dynamically resizes

Flexbox Is One-Dimensional

Flexbox is designed for one-dimensional layouts:

  • Use it to layout items in a row (horizontal axis)
  • Use it to layout items in a column (vertical axis)

For two-dimensional layouts (rows and columns), consider using CSS Grid instead.


Basic Flexbox Structure

Result: Items are laid out in a row and share equal space because of flex: 1.


Primary Flexbox Properties

For the Container:

  • display: flex – activates flexbox
  • flex-direction – sets main axis (row/column)
  • justify-content – aligns items on main axis
  • align-items – aligns items on cross axis
  • align-content – aligns rows in wrapped layout
  • flex-wrap – allows items to wrap
  • gap – spacing between items

For the Items:

  • flex – shorthand for grow, shrink, and basis
  • flex-grow, flex-shrink, flex-basis
  • align-self – override alignment per item
  • order – change display order

Example: Changing Direction

This stacks items vertically instead of horizontally.


Best Practices

  • Always use display: flex on the parent
  • Use gap instead of margin for spacing
  • Combine justify-content and align-items for precise control
  • Use flex-wrap for overflow handling on small screens

Example: Flexbox Properties in Action


Key Takeaways

  • Flexbox is for one-dimensional layouts
  • Use display: flex on the container
  • Align, space, and wrap items using container and item properties
  • Use flex, order, align-self for advanced layout control
  • Ideal for navigation menus, card layouts, toolbars, and responsive sections

Last Updated

12 July, 2025