Home > Enterprise >  Swap 1-2 and 5-6 div order using css only
Swap 1-2 and 5-6 div order using css only

Time:09-27

here is the challenge I'm trying to figure out. I need to swap A - B and E - F divs in reverse order using css, but C - D leave as it is.

Here is the code I'm using JSfiddle

<style>
.column div {
  display: block;
  border: 1px solid red;
  margin: 0 auto 20px;
  text-align: center;
  width: 300px;
}
</style>

<div class="column">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
  <div>F</div>
</div>

Image shows the problem

CodePudding user response:

Explanation

As other's have mentioned already, you could try leveraging the CSS property order inside a container with display: flex. By default elements are rendered in the order they appear in the document but you can change the ordering through that property.

Demonstration

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

.column > div {
  display: block;
  border: 1px solid red;
  margin: 0 auto 20px;
  text-align: center;
  width: 300px;
}

.column > div:nth-child(2) {
  order: -1;
}

.column > div:nth-child(5) {
  order: 1;
}
<div class="column">
  <div>A</div>
  <div>B</div>
  <div>C</div>
  <div>D</div>
  <div>E</div>
  <div>F</div>
</div>

Additional resources

You can always check A Complete Guide to Flexbox for more explanation on the CSS flexbox.

  • Related