2 min read

CSS Flexbox (Flexible Box Layout)

The Flexible Box Layout Module, makes it easier to design flexible responsive layout structure without using float or positioning.

1. The Concept

The Flexbox model allows elements within a container to automatically arrange themselves depending on screen size. It consists of a flex container (the parent) and flex items (the children).

2. The Flex Container

To start using Flexbox, you need to define a flex container.

.container {
  display: flex; /* or inline-flex */
}

flex-direction

Defines in which direction the container wants to stack the flex items.

  • row (default): Left to right.
  • column: Top to bottom.
  • row-reverse: Right to left.
  • column-reverse: Bottom to top.

flex-wrap

Specifies whether the flex items should wrap or not.

  • nowrap (default): All items will be on one line.
  • wrap: Items will wrap onto multiple lines, from top to bottom.

justify-content (Main Axis)

Aligns the flex items along the main axis (horizontal if flex-direction is row).

  • flex-start (default)
  • flex-end
  • center
  • space-between
  • space-around
  • space-evenly

align-items (Cross Axis)

Aligns the flex items along the cross axis (vertical if flex-direction is row).

  • stretch (default): Stretch to fill the container.
  • flex-start: Top of the container.
  • flex-end: Bottom of the container.
  • center: Center of the container.
  • baseline: Aligns items based on their text baseline.

align-content

Aligns flex lines (only works when there is wrapping and multiple lines). Similar values to justify-content.

3. The Flex Items

order

Specifies the order of the flex items. Default is 0.

.item { order: 1; }

flex-grow

Specifies how much a flex item will grow relative to the rest of the flex items. Default is 0.

.item { flex-grow: 1; } /* Takes up available space */

flex-shrink

Specifies how much a flex item will shrink relative to the rest of the flex items. Default is 1.

flex-basis

Specifies the initial length of a flex item.

.item { flex-basis: 200px; }

flex (Shorthand)

Shorthand for flex-grow, flex-shrink, and flex-basis.

  • flex: 0 1 auto (Default)
  • flex: 1 (Grow to fill space)

align-self

Overrides the align-items alignment for a specific flex item.

.item { align-self: center; }

programming/css/css programming/css/css3