CSS

Flexbox: Alignment

Adding shorthand flex:1 to each items is indeed handy.

A
B
C

But what it does is only to ignore all predeclared width, and distribute the space evenly between each items. It also doesn't say anything about vertical alignment. Here is how to have more control over alignments of the flexbox.

Properties to control alignments


justify-content

Controls alignment of all items on the main axis

If direction is reversed, of course the start and end are also flipped

If the axis is changed, justify content is applied to the vertical space.

margin: auto

There are no justify-items or justify-self properties. How to part the first few items to the left and the rest to the right? Using margin-left: auto on the first item pushed to the right or margin-right: auto on the previous item.


align-items

Controls alignment of all items on the cross axis.


align-self

Controls an individual flex item on the cross axis.

You can set align-items property on container that works for each items, or do it at individual item with align-self property. The values are the same, plus align-self: auto which reset the value to what is defined at the flex container.

Note on align-self: baseline: Items with baseline value will base-align among themselves. So if there's only 1 with such value, it will just go to the top instead.

Container below is set with align-items: center

stretch
baseline
flex-start
baseline
flex-end
center
auto
undefined

Let's play with flex-direction on above container

flex-direction: row-reverse
stretch
baseline
flex-start
baseline
flex-end
center
auto
undefined

For the vertical flexbox, predefined container's height is removed.

flex-direction: column
stretch
baseline
flex-start
baseline
flex-end
center
auto
undefined
flex-direction: column-reverse
stretch
baseline
flex-start
baseline
flex-end
center
auto
undefined

It seems like the baseline value doesn't take effect here. I have tried adding padding or margin as well to one of the item with baseline value, but it only send that box away from the left container border, but doesn't affect the other one.


align-content

Controls the distribution of space between rows in wrapped multiplt-line flex container. See packing flex lines.

Without align-content declaration:

align-content:
flex-start
flex-end
center
space-between
space-around
stretch
space-evenly

gap

The flex container below is set to:

A
B
C
D
E
F
G
H
I
J

To create gap between flex items: