What is Flexbox?
Flexbox is a set of CSS properties that provide a flexible way to lay out content.
Flex Container
The first step in any flexbox layout is to create a flex container.
Flex Item
Every direct child of a flex container is called a flex Item.
Note: An element can be both a flex item and a flex container, whereas a flex item will accept flex container properties when it’s displayed flex
or inline-flex
.
Main & Cross Axis
Flexbox follows two axes that determine the layout direction of flex items.
Everything in a flexbox layout is relative to the main axes.
Main Axis
Axis through which the items are listed.
It defines the primary direction of flex items inside a flex container.
Cross Axis
The axis perpendicular to main axis.
Flexbox Cheatsheet
.flex-container {
display: flex / inline-flex;
flex-direction: row / row-reverse / column / column-reverse;
flex-wrap: no-wrap / wrap / wrap-reverse;
justify-content: flex-start* / flex-end / center / space-around / space-between;
align-items: flex-start / flex-end / center / stretch* / baseline;
}
.flex-item {
margin-right: auto;
order: ... -2, -1, 0, 1, 2, 3, ... ;
flex-grow: 0, 1, 2, 3, ... ;
flex-basis : 200px;
align-self: flex-start / flex-end / center / stretch* / baseline;
}
order
— A flex container automatically gives all of its items a default order
value of 0
.
justify-content
— A flex container’s justify-content
property controls the margin value of a items.
flex-grow
— Enlarge item size by multiple folds.
flex-shrink
— Shrinks item size by multiple folds.
flex-basis
— Item’s min-width before breaking.
align-items
— Aligns items across the the cross axis.
align-self
— Aligns an item across the the cross axis.
Shorthand flex
.flex-item {
flex: 1 200px;
}
flex
: flex-grow
flex-shrink
flex-basis
;
Centering Items
Method #1
.container {
justify-content: center;
align-items: center;
}
Method #2
.container {
justify-content: center;
}
.item {
align-self: center;
}
Method #3
.item {
margin: auto;
}