iantresman iantresman - 21 days ago 5
CSS Question

Can flexbox sidebars share a new row?

Can I get flexbox sidebars to share a new row, after a media query?

Before (on wide screens)

+---+-------+---+
| | | |
| L | Main | R |
| | | |
+---+-------+---+


After (on narrow screens)

+-------+
| |
| Main |
| |
+-------+
| | |
| L | R |
| | |
+-------+


HTML (not changeable after media query)

<div class="container">
<div class="sideLeft">L</div>
<div class="MainContent">Main</div>
<div class="sideRight">R</div>
</div>

Answer

You can change order: -1 on main div with media queries. You also need to set flex-wrap: wrap on container element. Also calc(% - 10px) is for margin of 5px on both sides but if you don't want margins you can just use % as you can se here

* {
  box-sizing: border-box;
}
.container {
  display: flex;
  flex-wrap: wrap;
  height: 200px;
  border: 1px solid gray;
  padding: 5px
}
.container > div {
  display: flex;
  border: 1px solid black;
  margin: 5px;
  flex: 1;
}
div.main {
  flex: 3;
}
@media(max-width: 480px) {
  div.main {
    order: -1;
    flex: 0 0 calc(100% - 10px);
  }
  .container > div:not(.main) {
    flex: 0 0 calc(50% - 10px);
  }
}
<div class="container">
  <div class="sideLeft">L</div>
  <div class="main">Main</div>
  <div class="sideRight">R</div>
</div>