Learning CSS, I remember how amazing it was to start using flex and grid instead of fighting with the elements trying to position them with the position property. And while the position is still valuable for certain cases, I find myself predominantly using flex (for simple components) as it gives me enough flexibility to place everything where I want, with a couple of pretty simple properties. So, I thought I’d share three of my currently favorite flex properties that are easy to implement.
Using flex with a group of elements that include a button makes the button stretch to fill the height/width of the container. Regulate this by using align-self: start (or end, center – whichever you prefer) for the button element. This way it will not stretch and you can make it just the perfect size with further styling.
When I create a page layout that has a header and a footer and some content that fills the main section, I want that section to occupy the whole screen space between the header and the footer. The fastest way I found to do this is to use the flex-grow property (shorthand flex). It is specified as a number and the element with the highest number will take proportionally more space compared to the other elements. This is quite handy for regulating elements’ sizes. In the case I mentioned before, I’d just add flex: 1 to my main section, and then it fills the space that’s available between the header and the footer. However, do remember that the parent needs to have display: flex for any of the magic to happen and the body element needs min-height so that flex would know what space to work with (I am used to setting min-height: 100vh).
Flex is very helpful when positioning links in the navbar. The thing I use over and over again when creating simple headers is the flex display for all the elements in the header (and these are usually the logo and the navigation links). I want to separate those and give each their own place to shine. That’s where justify-content: space-between does the trick. You can use justify/align with different space options (check this cheatsheet to see more) that allow you to distance the element. The space-between puts the first element at the start and the last one at the end which is what I want with the logo and the links occupying the header.
As the cheatsheet I linked illustrates flex can do a lot more and is great to use for one-dimensional or single-line layouts.