Flexbox basics

CSS Flexbox is a powerful layout tool for arranging elements in a responsive and adaptable way, making it a go-to solution for modern web design.

Begin with setting display: flex to activate Flexbox on a container, allowing for better management of its child elements.

Directional flow

Control the direction of child elements with flex-direction:

  • row: for left-to-right
  • row-reverse: for right-to-left
  • column: for top-to-bottom
  • column-reverse: for bottom-to-top

Aligning items

Use alignment properties to place items:

  • align-items: for vertical control (top, center, bottom, stretch)
  • justify-content: for horizontal control (start, center, end, space between, space around)

Spacing between items

Adjust space between items using gaps to maintain consistent spacing.

  • row-gap: set the space between items vertically
  • column-gap: set the space between items horizontally

Wrapping items

Prevent overcrowding with flex-wrap, which moves items to the next line within the container when there’s not enough space.

Flex child properties

Flex children can be sized using flex-grow, flex-shrink, and flex-basis. These properties determine how much a child element will expand or contract relative to the available space in the container.

  • flex-grow: This property defines how much a flex item should grow relative to the rest of the flex items if there is extra space in the container. For example, a flex-grow value of 2 means the item will grow twice as much as an item with flex-grow value of 1.
  • flex-shrink: This property determines how much a flex item should shrink relative to the other items when there is not enough space. A value of 1 means the item will shrink at an equal rate compared to other items.
  • flex-basis: This property sets the initial main size of a flex item before any available space is distributed. It can be set to a specific width, height, or content size, and it determines the default size of the item before flex-grow or flex-shrink are applied.

Order and alignment

Rearrange the order of child elements with the order property, and individually align them with align-self, overriding the container’s default alignment settings.

If you need a bit more complex structure with columns and rows, grid might be a better solution.