Flexbox

Flexbox: A layout method for arranging items in rows or columns. Items will either shrink or expand (hence the “flex”- ibility part of the name).

Flexbox is built-in to CSS, so there’s no need to download any external CSS resources.

To start using it:

element {
  display: flex;
}

Flexbox Properties

justify-content

justify-content aligns items horizontally and accepts the following properties:

  • flex-start: start of the container
  • flex-end: end of the container
  • center: center of the container
  • space-between: items display with equal spacing between them
  • space-around: items display with equal spacing around them

align-items

align-items aligns items vertically and accepts the following properties:

  • flex-start: top of the container
  • flex-end: bottom of the container
  • center: vertical center of the container
  • baseline: baseline of the container
  • stretch: stretched items to fit the container

To center an element both horizontally and vertically we could do:

element {
  display: flex;
  justify-content: center;
  align-items: center;
}

flex-direction

The flex-direction CSS property defines the direction of the items placed in the container element. It accepts the following values:

  • row: Items are placed the same as the text direction
  • row-reverse: Items are placed opposite to the text direction
  • column: Items are placed top to bottom
  • column-reverse: Items are placed bottom to top

flex-wrap

The flex-wrap property accepts the following values:

  • nowrap: Every item is fit to a single line
  • wrap: Items wrap around to additional lines
  • wrap-reverse: Items wrap around to additional lines in reverse

flex-flow

The two properties flex-direction and flex-wrap are used so often together that the shorthand property flex-flow was created to combine them. This shorthand property accepts the value of the two properties separated by a space.

element {
  display: flex;
  flex-flow: column wrap;
}

align-content

align-content: Aligns the lines in a flex container when there is extra space on the cross-axis (normally horizontally).

flex-start: Lines are packed at the top of the container.

flex-end: Lines are packed at the bottom of the container.

center: Lines are packed at the vertical center of the container.

space-between: Lines display with equal spacing between them.

space-around: Lines display with equal spacing around them.

stretch: Lines are stretched to fit the container.

To practice display: flex and the four properties described above, try Flexbox Froggy game.


Individual Item Properties

  • order: default value is 0. We can reorder items using positive or negative integer values.

  • align-self: Accepts the same values as align-items for the specific element.

#css