Search code examples
htmlcssflexboxstylescss-grid

How to use FlexBoxes for a responsive Grid


I'm trying to use flex boxes to build a responsive grid that reorder it's items based on the expanded item.

Here's my HTML

<div class="flex">
  <div class="box1">
    Box1
  </div>
  <div class="box2">
    Box2
  </div>
  <div class="box3">
    Box3
  </div>
  <div class="box4">
    Box4
  </div>
</div>

Here's my CSS

.flex
{
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

.flex > div
{
   flex: 0 0 50%;
   text-align: center;
   border:  1px #ccc solid;
}


.flex > .box1 {
  flex: 0 0 100%;
}

Here's a working version - http://jsfiddle.net/pwr6xnd8/3/

This is how I want the boxes to function:

  1. When Box1 is expanded row1 should have only Box1 expanded and row 2 should now have Box2 and Box3. Row 3 should have only Box4 under Box2.

  2. When Box2 is expanded, row1 should only have Box 2 expanded but Row 2 should have Box1 and Box3. Row 3 should have only Box4 under Box1.

  3. When Box3 is expanded, row 1 should have Box1 and Box2 but row 2 should only have Box3 opened. Row 3 should only have Box4 to it's left.

  4. When box 4 is expanded, row 1 should have Box1 and Box2 but row 2 should only have Box4 opened. Row 3 should only have Box3 to it's left.

Right now for example when I opened the Box2, only Box1 stays in row 1 and Box 2 gets expanded in row 2 leaving Box 3 and Box 4 in row 4, which is clearly not what I want. Not exactly sure whether this functionality can be fully achieved using flexboxes or whether I might need some JS code in place.

Can anyone help on this please ?


Solution

  • I don't know you use any front end framework here or just HTML. As far as I got, just forget about the box numbers and when we focus on the design you can have a simple static layout like u shared fiddle.

    Therefore my suggestion is don't going to change the layout there. just change the content you need to put there according to your inputs or any available data.

    As an example. If you have more data that is related to 'BOX-4' you can decide to put it in that layout where you want (you can provide ids to div or you can use any method you want)


    If you have hard requirement to reorganize those elements you can use CSS grids that change element in both horizontal and vertical ways

    Here is the way to use CSS grid template https://www.w3schools.com/cssref/tryit.asp?filename=trycss_grid-template3 you can follow this and you can create templates for each scenario and change the CSS class dynamically with the way you want by applying those as conditional CSS.