Flexbox is a layout mechanism to layout items either horizontally or vertically next to each other.
Expands items to fill available space and shrinks to prevent overflow.
The items won’t wrap by default.
align-items
, justify-content
and flex-wrap
properties allow you to control how flex children elements behave with and around their sibling elements.
Flex container holds the flex items Flex items: Define properties on how the element should align and flow within the container
A flex layout has a main axis. If your flex direction is row
is it along the row, if the direction is column
, it is along the column. The other axis is called the cross axis.
direction, alignment, ordering, and flexibility
Properties
Children behaviour
align-items
:
flex-wrap
:
- The default is
nowrap
, such that if there is not enough space in the container, items will overflow. - Using
wrap
, items might wrap.
A common shortcut to combine flex-wrap
and flex-direction
is: flex-flow
The shortcut for flex-shrink
, flex-grow
and flex-basis
is simply flex
. The following setting makes sure items have automatic size and can grow and shrink: flex: auto
Direction
Use flex-direction
for it. By defaut it is row.
row: Elements appear in a row column: Elements appear stacked as a column.
Alignment
justify-content
: space distribution on the main axis.align-content
: space distribution on the cross axis.place-content
: a shorthand for setting both of the above properties.
justify-content
:
center
will center the elementsflex-start
: will align the items starting at the beginning of the containerspace-around
: will provide even space around the flex itemsspace-between
: will provide maximum space between the items (not to the flex start and end) so items will touch the corners mostly.
align-content
:
strech
: will force the items to strech across the cross axis- The other attributes are just as before
Attributes
display: flex;
align-items: center; /* vertical alignment */
justify-content: center;
flex-direction: row; /* row by default, left to right for the main axes*/
Dealing with children
To make the children of a flex-children treated as direct children, one can use display: contents
. But this does stop rendering other properties.
Compared to Grid
Grid:
- layout first
- Rigid layouting
- Rules decided by parent
- one-dimensional
- Mainly used for the overarching layout of the side
Flex:
- Content first
- Rules decided by children
- one-dimensional
- Mainly used for navigation layouts and other components