Search code examples
cssflexboxcss-gridgrid-layout

Grid vs Flex for implementations of Holy Grail-like layout


I want my layout to go from this when Sidebar is present:

enter image description here

To this when Sidebar is not present:

enter image description here

To get this effect, I believe three modern choices are to:

  1. Grid alone: have a grid that utilizes a class like this https://codepen.io/rajsinghusa/pen/ExPaXqR , or

  2. Grid+Flex: have a grid layout for 3 rows, with two flex items for the middle row. Or,

  3. Flex alone: use flex to create 3 rows and then two columns in the middle row.

How would these three implementations differ in their limitations?


Solution

  • Given your implementation details, I would say that the only difference is semantic. The three options will work well, for your use-case I think the grid is the one I would go since it's easy to see what's happening on the different layouts.

    Looking side by side at both declarations its very clear how the layout works:

    "header header" "sidebar main" "footer footer"
    "header header" "main main" "footer footer"
    

    I don't see a clear benefit in using options 2 or 3 given this use-case.

    An important thing to have in mind is how grid behaves compared to flex:

    Grid is Container-Based, Flexbox is Content-Based

    In flexbox layout, the size of a cell (flex-item) is defined inside the flex-item itself, and in the grid layout, the size of a cell (grid-item) is defined inside the grid-container.

    Source: https://www.webdesignerdepot.com/2018/09/grid-vs-flexbox-which-should-you-choose/

    Depending on how you want your layout to behave, how it adapts to different screen resolutions or different content this difference is good to have in mind. Again I think grid will give more options in this regard.