Using Flex-Grow

Sanjar Kairosh
February 15th, 20213 min read
Photo by Curology on Unsplash

I used the flow-grow property to align the last item at the end of a flexbox with respect to the preceding flex items.

If you need to align some elements within a relative container, it is more likely than not that you are using the CSS flexbox module. It’s amazing how flexible and neat this module is. I remember when I used to align items using float .

Align the Last Item All the way to the right

Let’s say you have a couple of tabs in a navigation bar, and you want all but the last item to be on the left of the navigation bar, while the last item should be all the way to the right.

If the items are aligned using flexbox, you can use the property flex-grow to set the last item all the way to the right.

https://codepen.io/san_coder13/pen/MWbpBbB

Flex Grow

This sub-property of flex items essentially dictates how much of the remaining space a flex item should take. There is remaining space if the total width of the items is smaller than the flexbox container. If no flex-grow properties are set on any of the items, the remaining space will remain unclaimed, after the last item.

Let’s say you want to distribute the remaining space equally among all items. You simply need to set flex-grow: 1; for each item. If there were four items as in the navigation bar in the Codepen example above, a total of 4 units of space were just distributed. Since each item had flex-grow: 1; each item occupied 1/4 of the remaining space.

Similarly, if only one of the items was given the flex-grow: 1; property, that specific item would take on 1/1 of the distributed remaining space. The item would i.e. take on all of the remaining space.

Flex-grow is about proportions. In my case, I needed to align the last navigation tab all the way to the right. I decided to allocate all of the remaining space for the tab preceding the very last tab. This third item would take on all of the space that was initially to the right of all the tabs, and push the last tab all the way to the end.

If I wanted to push the last two items all the way to the right, I would have to set flex-grow: 1; on the second navigation tab.

Flexbox aligns all the navigation tabs to the left and leaves the remaining space on the right since the tabs don’t require all of that space. To distribute all of the remaining space among the tabs, I would simply set flex-grow: 1 for each tab.

This same logic would work for a flexbox aligned vertically as a column. Setting flex-grow on some of the elements would push the successive elements to the bottom.

Blogs

copyright ©2021 all rights reserved, Sanjar Kairosh
illusrations by icons8