Flex Item Alignment

This should all start to be somewhat familiar to you now. CSS grid and Flexbox share many common patterns and alignment is no different.

Aligning on the Main Axis

On the main axis, justify-content is the property that determines the alignment and distribution of flex items along the main axis. It also allows us to control how available space is handled if needed.

.flex-container {
    background-color: rgb(171, 174, 180);
    padding: 1em;
    display: flex;
    justify-content: space-between;
}

The justify-content property will accept the following values:

  • flex-start (default): Items are packed on the start of the main axis
  • flex-end: Items are packed on the end of the main axis
  • center: Item are centered along the main axis
  • space-around: Items are evenly distributed in the line with equal space around them
  • space-between: Items are evenly distributed in the line; first item is on the start line, last item on the end line
  • space-evenly: Items are distributed so that the spacing between any two adjacent alignment subjects, before the first alignment subject, and after the last alignment subject is the same
Box 1
Box 2
Box 3
Box 4

Aligning on the Cross Axis

Alignment of items along the cross axis is accomplished through the use of align-items and align-self.

With align-items applied to the container, all direct flex items will be styled accordingly. align-self provides an override that is applied at the item/child level.

.flex-container {
    background-color: rgb(171, 174, 180);
    padding: 1em;
    display: flex;
    flex-flow: row wrap;
    align-items: center;
}
Box 1
Box 2
Box 3
Box 4

align-content provides some distribution capability that align-items does not but the flex container requires more height (available space) than required to display the items.

.flex-container {
    background-color: rgb(171, 174, 180);
    padding: 1em;
    display: flex;
    height: 20em;
    flex-flow: row wrap;
    align-content: space-between;
}
Box 1
Box 2
Box 3
Box 4

Further Review

References