How can I order a child flex element ahead of its parent?

Viewed 60

I have the following HTML/CSS setup (jsFiddle):

.flex-container {
  display:flex;
  flex-direction:column;
}

.one, .two, .three {
  flex: 0 0 auto;
}

.one {
  order:0;
}

.two {
  order:1;
}

.three {
  order:2;
}
<div class="flex-container">
  <div class="three">
    <div class="one">One</div>
    <div>Three</div>
  </div>
  <div class="two">Two</div>
</div>

As you can see, my aim is to order div .one at the top. The problem is that this div is inside a flex div with a different order.

What I've tried so far

  1. position:absolute or fixed on .one. While that works, I need all the divs to be blocks.
  2. I have move the .one div to the parent div using javascript, but the aim is to do this without JS.

Any viable solution to this?

1 Answers

I believe you're missing the whole concept behind order. It's designed to allow re-arranging of siblings. If you want to display .two between .one and .three at a certain screen width and outside of them at other widths:

  • they should be siblings
  • there is absolutely no point in .one being a child of .three.

So, I'd use a mobile first layout:

.flex-container {
  display:flex;
  flex-direction:column;
}
.two {
  background-color: rgba(0,0,0,.05)
  }
@media (min-width: 768px) {
  .two { order:1; }
  .one,.three { order: 2; }
}
<div class="flex-container">
  <div class="one">One</div>
  <div class="two">Two</div>
  <div class="three">Three</div>
</div>

However, if .one must be a child of .three (btw, when you start using this verb in web development, it's solid sign you're doing it wrong) - your only choice is JavaScript. Now the problem with js driven @media queries is that you need to be a cross-browser/cross-device ninja to detect the change of @media query interval in all browser/device combos and that's why you should use enquire.js for it. And, of course, move .two around in DOM.


But really, since I tried my best to answer your question, it would mean a lot to me if you tried your best to answer mine: why does the markup need to remain unchanged? Does the markup matter? Or does the way your contents are displayed cross-browser/cross-device matter?

Related