Neat responsive flexbox layout


by Jeremy Caudle
code

If you haven’t heard of Heydon Pickering, I certainly recommending checking out his website heydownworks.com, and learning all about the things he makes regarding web design and development. I watched a video of Heydon’s CSS Day 2019 talk about the Flexbox Holy Albatross and tried it out in this post. I’m still trying to full wrap my head around it (I feel like I could make a flexbox joke there), but it’s definitely going to be handy in the future.

4 children - Changes basis at 50rem

1
2
3
4

2 children - Changes basis at 50rem

1
2

5 children - Automatically changes basis because of number of child elements.

1
2
3
4
5

View the code:

HTML and JS
<div class="code-block">
        <h2>4 children - Changes basis at 50rem</h2>
        <div class="flex-parent-parent">
        <div class="flex-parent">
       
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>

        </div>
        </div>

    <h2>2 children - Changes basis at 50rem</h2>
    <div class="flex-parent-parent">
        <div class="flex-parent">
       
            <div>1</div>
            <div>2</div>

        </div>
    </div>

    <h2>5 children - Automatically changes basis because of number of child elements.</h2>
    <div class="flex-parent-parent">
        <div class="flex-parent">
       
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
            <div>5</div>

        </div>
    </div>
CSS
.code-block {
                background-color: white;
                font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
            }
            
            /*Modification of Flexbox Holy Albatross by Heydon Pickering - http://heydonworks.com/
            Great video of this concept on YouTube - https://www.youtube.com/watch?v=RUyNJaoJH_k*/

            /* Fixes margins for flex-parent container */
            .flex-parent-parent {
                margin: -.5rem;
            }

            .flex-parent {
                display: flex;
                flex-wrap: wrap;
            }

            .flex-parent > * {
                flex-grow: 1;
                flex-basis: calc((50rem - (100% - 1rem)) * 999);
                margin: 0.5rem;
                background-color: black;
                text-align: center;
                color: gray;
                padding: .5rem;
            }

            /* .flex-parent > :nth-child(2) {
                flex: 2;
            } */


            /* Quantity query that adjusts flex-basis for flex-parent if there is over 4 child elements */
            .flex-parent > :nth-last-child(n+5),
            .flex-parent > :nth-last-child(n+5) ~ * {
                flex-basis: 100%;
            }