How to use CSS Flexbox on nested divs

Neer
3 min readAug 16, 2019

--

source: kachbow.com

CSS flexbox is one of the most popular choices while making complex website layouts. It is easy to use and works on all the modern browsers. However, it can be daunting to use on nested div elements for a complete beginner.

Therefore, I am going to share my learning experience from building projects in microverse program with flexbox on nested div elements. If you are beginner, and wondering why the div elements are not aligned, as it is supposed to be then this article is for you.

Flexbox is one dimensional layout.

What does this means and why does it even matter are some questions in beginner’s mind. This is totally fine because when we are building web layouts we don’t think about the flow of the content and it is easy to mess up when there is nested div elements.

Therefore, it is important to know that flexbox is either a row or a column meaning the content will flow from left to right or top to bottom. The concept of one dimensional layout enforces to think in either a row or a column that makes easier to fix the nested div elements.

Now we understand the concept of flexbox design layout, it is much easier to make content flow horizontally or vertically. I have created a gist with nested div elements and used the idea of one dimensional layout.

As you can see from HTML element, it has multiple layer of elements within element. To align these elements, I used flex direction row which is a default value in flexbox on both parent and child element. Afterwards, I used flex direction column to the grand child which makes last inner content flow both horizontally and vertically.

If you don’t add flex direction column in grand child the layout will collapse and it will no longer be vertical and horizontal. Therefore, we need to remember to use column in flex direction for the last content inside the nested div.

Result without flex-direction column
Final result with flex-direction column

Conclusion

By implementing the fundamental idea of flexbox, it is easy to fix and build any number of nested div elements. This is how I learned to use flex on my nested div elements. If you have any comments or anything in the code I would be more than happy to help. Keep learning and continue coding.

--

--

Neer

Digital minimalist, Learning to learn, Explorer