Using the flex order property across multiple containers

徘徊边缘 提交于 2019-12-23 12:41:04

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/45226114/using-the-flex-order-property-across-multiple-containers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!