1

I have a certain form that is made as angular directive template. It contains several INPUT fields in certain order. I can not construct that form dynamically using ng-repeat approach, because some fields have custom behaviour, special validators and such.

 <div ID="1"> input field 1</div>
 ...
 <div ID="7"> input field 7</div>

I however have a need to display these input in different random order under some use case. The logic and contents of form remains the same but just one input that used to be 7th should become 1st. It would be great if I can achieve it using a CSS class that is conditionally applied to certain elements (likely, using ng-class option).

What CSS I can possibly use to keep the same template (sketched above) but have visually "div id=7" to appear before "div id=1" ?

I prefer to avoid DOM manipulating and have it angular-friendly way.

onkami
  • 8,791
  • 17
  • 90
  • 176

2 Answers2

4

flexbox can change the visual order of elements using the order property.

.wrap {
  display: flex;
  flex-direction: column;
}
.wrap div {
  padding: 1em;
  border: 1px solid black;
  margin-bottom: 1em;
}
#first {
  background: #bada55;
  font-weight: bold;
  order: 7
}
#last {
  background: #663399;
  color: white;
  font-weight: bold;
  order: 1
}
<div class="wrap">
  <div ID="first">I'm first in the source order but not visually</div>
  <div ID="last">I'm last in the source order but visually I'm first</div>
</div>

After that, randomness can be added via Javascript and order assigned with a loop (I assume, my JS fu is basically non-existent).

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
0

Since div elements are block elements, so each div will appear on its row, and so it is not possible by just CSS to show the second one before the first.

But if you have this divs style as display:inline; or display:inline-block; for example with a width, then you will be able to play with float:right; float:left; to change the order.

also I google "change order of html elements by css" and it gave me some other ideas as well.

And there are some answers on stackoverflow as well like this one

Community
  • 1
  • 1
Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301