0

I have the following layout problem. 4 blocks one after the other a1,b1,a2,b2 in a column on mobile. On the desktop I want to get a1,a2,b1-b2 that is a1 followed by a2 followed by b1-b2 on same row but below a2. I was hoping to use flexbox but not sure how to go about this.

mobile:

<div style='display:flex;flex-direction:column>
    <div id='a1'></div>
    <div id='b1'></div>
    <div id='a2'></div>         //each of these is 100VW
    <div id='b2'></div>
 </div>

desktop:

    <div id='a1'></div>      // the first two are 100vw
    <div id='a2'></div>
    <div id='b1'></div><div id='b2'></div>  //each of these would be 50vw

Is there a way to do this with one version of the html and only modifying the css?

DCR
  • 14,737
  • 12
  • 52
  • 115
  • You're dealing in 2 dimensions, not 1, so look to Grid not Flexbox. – Quentin May 03 '20 at 21:23
  • This is about CSS and not the DOM. CSS has no effect on the DOM. You have also tagged this as jquery and javascript. Why? – Rob May 03 '20 at 21:56
  • @Rob, clearly it's about both. We need to change the flow from a1,b1,a2,b2 to a1,a2,b1,b2 – DCR May 03 '20 at 21:57
  • Well, neither flex nor any other CSS properties will change the DOM flow. – Rob May 03 '20 at 21:58
  • @Quentin, I see I can individually place each cell - is there a more elegant solution? – DCR May 03 '20 at 21:58

1 Answers1

1

Grid would be simpler, but it's also possible with flexbox.

flex

article {
  display: flex;
  flex-wrap: wrap;
}

#a1 { order: 1; }
#a2 { order: 2; }
#b1 { order: 3; }
#b2 { order: 4; }

div {
  flex: 0 0 100%;
  background-color: lightgreen;
  margin-bottom: 5px;
}

#b1, #b2 {
  flex: 1 0 34%; /* allows max 2 items per row, with ample space for margins */
}

#b2 {
  margin-left: 5px;
}

@media ( max-width: 500px) {
  article {
    display: block;
  }
  #b2 {
    margin: 0;
  }
}
<article>
  <div id='a1'>a1</div>
  <div id='b1'>b1</div>
  <div id='a2'>a2</div>
  <div id='b2'>b2</div>
</article>

jsFiddle demo


grid

article {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 5px;
  grid-template-areas:
    " a1 a1 "
    " a2 a2 "
    " b1 b2 "
}

#a1 {
  grid-area: a1;
}

#a2 {
  grid-area: a2;
}

#b1 {
  grid-area: b1;
}

#b2 {
  grid-area: b2;
}

@media (max-width: 500px) {
  article {
    grid-template-columns: 1fr;
    grid-template-areas:
      "a1""b1""a2""b2";
  }
}

div {
  background-color: lightgreen;
}
<article>
  <div id='a1'>a1</div>
  <div id='b1'>b1</div>
  <div id='a2'>a2</div>
  <div id='b2'>b2</div>
</article>

jsFiddle demo

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701