Flexbox display: flex;

The main axis and the cross axis

There are two invisible axis that control the flexbox.

  • The main axis that goes through the center of the box along the flex direction
  • The cross axis that is perpendicular to the main axis

flex-direction: row; defines the direction of the main axis, it can be set to row or column

We use justify-content to control the main axis, and align-items for the cross axis.

  • For the justify-content, the values can be:

    • flex-start: default
    • flex-end
    • center
    • space-between
    • space-evenly
    • space-around
  • For align-items we can use:

    • flex-end
    • flex-start
    • stretch: default
    • center

How the flexbox becomes flexible

There are three properties that makes elements inside flexbox shrink/grow

  • flex-basis: the basis of the shrink or grow, by default it is auto, which means it will use the width/height set to the item.
  • flex-grow: the ratio of how the item will expand when there is additional space, by default is 0, which means it will not grow.
  • flex-shrink: defines how much the item will shrink if the container is too small, by default is 1, which means the item can shrink

flex-wrap

By default, when there is not enough space, the items will shrink(because flex-shrink is 1 by default), but sometimes we want the page to be responsive by moving items to different rows.

That’s where we need flex-wrap. It have 3 values:

  • no-wrap: the default value, even if there is no space, the items will not be moved to a new line.
  • wrap: move items to new line when there is no space.
  • wrap-reverse: same as wrap but the new line will be above the existing line instead of below.

But a new problem comes in mind, align-items can only control alignment inside the row/column, what should we do if we want to align multiple rows/columns.

That’s where align-content comes into use. It also have many values:

  • flex-start
  • flex-end
  • center
  • space-between
  • space-around
  • stretch

But in order to use align-content, we must:

  • set the flex-wrap to wrap or no-wrap
  • there are at least two lines in the container(wrapped)

align-self

Just like in the grid, we can set the alignment of individual items using align-self to override the align-items property.

1
2
3
.flex-item {
align-self: flex-start;
}

In addition, we can use order to chang ethe virtual order of the items without changing the HTML.

1
2
3
.item {
order: -1;
}

The order property can be set to negative numbers, and the items will be placed in ascending order.
But note that it only changes the virtual order, that is the order they appear on the user interface, not in the DOM, therefore, we should avoid using it.