Tuesday, May 5, 2020

flex is flexible, but it's not griddable

<div id="band">
    <div style="background-color: red">John</div>
    <div style="background-color: green">Paul</div>
    <div style="background-color: blue">George</div>
    <div style="background-color: yellow">Ringo</div>
</div>


<style>
    body {
        background-color: slategray;

        display: flex;
        justify-content: center;
        align-items: center;
    }

    #band {
        background-color: white;

        margin: 0 auto;
        border-style: solid;
        border-width: 2px;

        max-width: 740px;
        width: 100%;

        display: flex;
        /* justify-content: flex-start; */ /* flex-start is the default justify-content */
        flex-wrap: wrap;
    }

    #band > div {
        width: 200px;
        height: 200px;

        /* center all the names inside each box */
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>


Its output is:




If we change the justify-content to center:
display: flex;
justify-content: center;
flex-wrap: wrap;


Not only the first row's items are centered, the last item will be centered as well, which is not we want:



If we want to wrap extra items at leftmost and keep the whole grid of items at the center, we need to use grid instead of flex, and replace flex-wrap: wrap to repeat autofit and minmax. To wit:
display: grid;
justify-content: center;
grid-template-columns: repeat(auto-fit, minmax(200px, max-content));

The output is correct:



On the above display grid and grid-template-columns settings, if we change the justify-content to end:
display: grid;
justify-content: end; /* flex-end works as well, but we will just be confusing ourselves with that, we are using grid not flex */
grid-template-columns: repeat(auto-fit, minmax(200px, max-content));

The output is:


To contrast with flex-end of display: flex:
display: flex;
justify-content: flex-end;
flex-wrap: wrap;

The output is:


Same settings above, but with five items:



Let's use grid again with justify-content of end:
display: grid;
justify-content: end;
grid-template-columns: repeat(auto-fit, minmax(200px, max-content));

Its output:



This flex's flex-start:
display: flex;
justify-content: flex-start;
flex-wrap: wrap;

And grid's start:
display: grid;
justify-content: start;
grid-template-columns: repeat(auto-fit, minmax(200px, max-content));

Have same output:

No comments:

Post a Comment