Flexbox – how I finally begin to understand and love it!


Since I first heard of Flexbox Layout Module, I’ve always been kind of intimidated by it because I don’t see myself as a “web design” guy ((But I strive to be a self-sufficient when it comes to building websites and web apps)). I’ve heard its main selling point of creating layout easier and even used ready-made solutions from the Internet when I needed to solve some CSS problem but I’ve never had a real, in-depth understanding of Flexbox.

Until recently, when I was designing a website for WordPress for local handball club. In the first version I was coding layout in an old-fashionable way:

  1. using floats to display posts in a grid 2 per row and
  2. .post {
        float: left;
        width: calc(50% - 1em);
        margin-right: 1em;
    }
    
  3. absolute positioning to create a sidebar that has a custom background and was spanning to 100 % height of its parent no matter how much content it has.
  4. .site-content {
        width: 80%;
    }
    .widget-area {
        position: absolute;
        top: 0;
        right: 0;
        height: 100%;
    }
    

The first problem is solvable just fine but in the second I also needed to set the width of its sibling (main or primary content) so it doesn’t get behind absolute positioned sidebar. And the sidebar overflows its parent if it has more content height-wise than its sibling. And since I’m here complaining about using this old-fashionable approach, I’ll also mention that I wasn’t satisfied how the first problem was solved either. Left aligned children would look much more pleasant if they would be of equal height, but they weren’t.

Enter flexbox!

I remembered again flexbox technique and found two resources on Medium (flexbox explained with animated gifs by Scott Domes). I also signed up for flexbox course by Sean Fioritto which also presents Flexbox concepts in animated way but using JavaScript ((Which by the way is really cool, so kudos to the author.)). And slowly I began to master/finally understand it.

When I first applied learned to the first problem, I was impressed that it automatically created children with equal height thanks to the correct default value of the specific flexbox-related property. Beside declaring container’s display as flex, I also declared flex-wrap to allow aligning children in multiple rows where each child has a width of 50% of its parent width (with wrap value). The specific flexbox-related property is align-items and its default value is stretch, meaning take up all available container’s space height-wise.

.site-main {
    display: flex;
    flex-wrap: wrap;
}

.post {
    width: calc(50% - 1em); // could use flex-basis instead of width 
    margin-right: 1em;
}

Flexbox solution to the second problem is even easier. Declaring container’s display as flex is enough as align-items‘ default value do all the hard work.

So at the end I was like:

Flexbox so much WIN