27

I would like to achieve something that renders like this, depending on the screen size:

+---------------------------+
|  A  |       B       |  C  |
+---------------------------+

+---------------+
|   A   |   C   |
|       B       |
+---------------+

If all size are fixed, I can manage using the flex order property but the size of my C container is not fixed and so I can't use a static media query.

Is there a way to achieve this?

Edit: I managed a good enough approximation: In a media query selecting all screens that might need wrapping, I change the order of the B container to something big, and at the same time, I set its min-width to 100% which forces the wrap.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Arthur
  • 4,093
  • 3
  • 17
  • 28

1 Answers1

20

You can make b element full width with flex: 0 0 100% and change order to order: 2 with media queries DEMO

* {
  box-sizing: border-box;
}
body, html {
  margin: 0;
  padding: 0;
}
.content {
  display: flex;
  flex-wrap: wrap;
}
.b {
  background: lightblue;
}
.a, .b, .c {
  border: 1px solid black;
  flex: 1;
  padding: 10px;
}
@media(max-width: 768px) {
  .b {
    flex: 0 0 100%;
    order: 2;
  }
}
<div class="content">
  <div class="a">A</div>
  <div class="b">B</div>
  <div class="c">C</div>
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • 11
    Unfortunately this won't work when the sizes of `a`, `b`, and `c` aren't known in-advance or are variable at runtime. – Dai Mar 23 '21 at 20:54
  • @Dai - if flex-wrap only 2 childs, inverting order of elememnts in HTML and `flex-direction: row-reverse` may be your solution SOURCE: http://www.java2s.com/example/html-css/css-layout/change-the-order-of-flex-items-when-they-wrap.html – Botea Florin Jun 09 '23 at 09:28
  • @BoteaFlorin This QA is about having 3 or more children, not 2 (and java2s.com is not an authoirtative resource for web-development). – Dai Jun 09 '23 at 19:32
  • @Dai I came to this question because I was in a similar situation, but with 2 elements. java2s.com gave me the idea that you may change the actual order of html elements in code like: A C B and use flex order property to put B before C. This may work (not tested it, but is similar). There is no special selector for flex > item::wrapped – Botea Florin Jun 10 '23 at 08:09
  • @BoteaFlorin flex order won't work for the reasons I described above: you cannot reorder elements based on their content size, and if the size of the content isn't known in-advance then you can't use known-sizes in `@media` queries or Container Queries. – Dai Jun 10 '23 at 18:32
  • @Dai you were right – Botea Florin Jun 10 '23 at 20:52