80/20 Flexbox Notes
The basic principle is that items expand and shrink to fill the space
given by the flex container. Flex containers are any element that has
been given the property of
display: flex;. It will act as a
block level element, and by default will force all of its children
(flex items) to fit on a single X axis.
The following write-up is a refresher on some of the key properties. To dive deeper consider checking out the MDN Flexbox Docs.
Use flex-direction: row | column | row-reverse | column-reverse; in order to change main axis that flex items are laid out in. It is often recommended that you avoid the reverse properties, as they can cause accessibility implications with regards to screen readers. Once these it can be useful to imagine the properties align-items and justify-content having swapped their functions.
The default setting is flex-wrap: nowrap; will will contain all of the flex items within the main axis. In order to change this use flex-wrap: wrap;.
Vertical alignment is done using align-items which defaults to stretch causing all flex items to become as tall as the tallest flex item. You will usually want to give all flex-items independent heights using align-items: flex-start; or center them using align-items: center;
For grouping items together you can use
For laying out items you can use space-around, space-betweenor space-evenly
A super useful tool for adding spacing between flex items is the gap property on the flex container, e.g. gap: 1rem;. This will add spacing between items and not on the outer edges. Note that this is only supported on browsers after circa 2021.
Size of flex items (children)
One way is to give each flex item a proportional unit of space. For
example item 1 has flex: 1; and
item 2 has flex: 2;. In this
example item 1 would take up 1/3 of the space, and item 2 would take
up 2/3 of the space.
A usual way to improve this is to give the flex property a minimum size value as the second parameter: flex: 1 200px; . If this value is given to both item 1 & 2, then both would be given at least 200px of available space, and then the rest of the available space would be proportionally allocated according to the first parameter.
This flex property is shorthand for the properties flex-grow , flex-shrink and flex-basis which typically are better handled and easier to understand by using the shorthand. Out of these the most useful is flex-shrink, which is great when a you have a specific element that would look strange if it was not given the exact width that it required, for example a circle with an icon inside it next to more dynamic elements such as text.