About Flexbox
THE OLD WAY
Before flexbox you had to use floats and complicated math to layout a website. This was frustrating and never worked the way you wanted. This is because they way you want to use it is not the way it was designed to be used. Floats were only created to allow text to flow around images.
Vertical centering before flexbox was one of the most prevalent problems in web design. Many solutions involve fixed size containers, carefully calculated margins that could break at any moment, or the relatively simple solution below. All of these solutions however, involve too much work for such basic tasks.
.container{
position: relative;
}
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
THE NEW WAY
Hacking and entire layout is obviously not ok, so the internet gods created flexbox. Flexbox was designed specifically to make coding layouts easier. Flexbox allows a container to adjust its child elements width, height, order, and spacing in all directions.
Vertical centering with flexbox is extremely simple thanks to its ability to automatically space elements in both horizontal and vertical directions.
.container{
display: flex;
justify-content: center;
align-items: center;
}
Terminology
- Flex line - Line along which flex items are aligned
- Main axis - Axis along which flex items flow. It can be horizontal or verticle
- Main-start & Main-end - The begining and end of the main axis
- Main size - The width of height of flex items depending on the flex-direction
- Cross axis - Axis perpendicular to the main axis
- Cross-start & Cross-end - The begining and end of the cross axis
- Cross size - Similar to main size by in the perpendicular direction
Flexbox is not without its faults
- Flex items are dynamically sized so they can cause the page to jump around as it loads
- Flex items dont honor their minimum size when shrinking
- Some elements like
<fieldset>
and<button>
can not be flex containers - IE has its own issues
-
- When in the column direction
align-items: center
will cause content to overflow the container - Giving a flex container a
min-height
won't affect its children - The
flex
shorthand must have units on theflex-basis
value - Images in flex columns will not have their aspect ratios preserved
- The default value for
flex-shrink
is 0 box-sizing: border-box
does not work onflex-basis
calc()
is not fully supported onflex-basis
- Inline elements can not be flex items
important
does not work on theflex-basis
part of theflex
shorthand
- When in the column direction