Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the flex order property across multiple containers

Tags:

html

css

flexbox

If I have the following HTML markup:

<div class="wrapper">
  <div id="container-1">
    <div class="child-1-1"></div>
    <div class="child-1-2"></div>
  </div>
  <div id="container-2">
    <div class="child-2-1"></div>
    <div class="child-2-2"></div>
  </div>
</div>

I can apply a display of flex to wrapper, and then make container-2 appear above container-1 using order.

I would like the final order of the elements to be:

  1. child-2-1
  2. child-1-1
  3. child-1-2
  4. child-2-2

What I basically want is for the children of the two containers to pretend as if their parents are not there, and instead take their ordering from the outer wrapper.

This could of course be achieved via either duplicating the components and hiding/showing depending on the breakpoint, or via JS - so no points for suggesting those.

like image 772
Geat Avatar asked Oct 17 '22 08:10

Geat


1 Answers

The flex order property applies only to siblings in the same container.

So using order to re-arrange a series of flex items spread across different containers will not work.

But based on your requirements, it doesn't appear you need multiple containers. All items can exist in a single container.

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.child-1-1 { order: 1; }
.child-1-2 { order: 3; }
.child-2-1 { order: 2; }
.child-2-2 { order: 4; }

.wrapper > div {
  flex: 1 0 40%;
  height: 50px;
  margin: 5px;
  border: 1px solid #ccc;
  background-color: lightgreen;
  display: flex;
  align-items: center;
  justify-content: center;
}


@media ( max-width: 600px) {
  .wrapper {
    flex-direction: column;
  }
  div.child-2-1 {
    order: -1;
    background-color: orange;
  }
}
<div class="wrapper">
  <div class="child-1-1">child-1-1</div>
  <div class="child-1-2">child-1-2</div>
  <div class="child-2-1">child-2-1</div>
  <div class="child-2-2">child-2-2</div>
</div>

jsFiddle

Learn more about the flex order property here:

  • Is there a “previous sibling” CSS selector?
  • Flex order property not working as expected
like image 57
Michael Benjamin Avatar answered Oct 21 '22 02:10

Michael Benjamin