Getting started with Flexbox
Grid and Flexbox are different in many ways, but they share a lot of similarities as well.
The first one is, when we declare display: flex, we are changing the context inside of that element. The element where we declare it becomes a Flex Container and the children become Flex Items.
While Grid is fantastic at creating more strucutured layouts where the content lives, Flexbox is better suited for creating intrinsic layouts where the content itself has a lot more control.
All we need to do to get started with Flexbox is declare display: flex;, and a gap can be handy as well.
.flex-container { display: flex; gap: 16px;}See the Pen Getting started with Flexbox by Kevin (@kevinpowell) on CodePen.
As we can see when turning display: flex on and off, Flexbox allows children to have a significant impact on how the layout looks.
- Each element becomes the size of the content inside of it
- If there isn’t enough room, it’ll start to shrink
There is a lot more to Flexbox than this, but if you can just remember that this is how it wants to work without any extra finagling, you’re already ahead of how most people think about it.
Preventing overflow with Flexbox
Section titled “Preventing overflow with Flexbox”Flexbox is good at creating flexible layouts, but that doesn’t mean those layouts are perfect. It will quickly run into overflow issues if there isn’t enough room for all the elements to be next to one another other.
Luckily for us, there is a very simple and intrinsic solution that we can use here: the flex-wrap property.
The default value for flex-wrap is nowrap (annoyingly, without a hyphen).
If we switch that over to wrap, then our overflow issues go away.
.flex-group { display: flex; flex-wrap: wrap; gap: 16px;}Simply declaring a display: flex; along with a gap an flex-wrap: wrap will be something you do a lot.