DEV Community

Nijeesh Joshy
Nijeesh Joshy

Posted on

Sorting HTML elements with Flexbox and JavaScript

What is flexBox

flexbox or flexible box layout is a layout scheme in CSS. which is used to align and organize HTML elements in a layout.

let say this is our HTML layout

<div class="row">
  <div class="col " id="">1</div>
  <div class="col " id="">3</div>
  <div class="col " id="">5</div>
  <div class="col " id="">200</div>
  <div class="col " id="">4</div>
  <div class="col " id="">2</div>
  <div class="col " id="">400</div>
</div>

to use the flexbox properties we have to change the display: type of the parent to flex

.row {
  display: flex;
}

for making the elements appear in a column instead of a row we have to set the flex-direction.

it can have values row, row-reverse, column, column-reverse;

so getting the column layout we add flex-direction: column to our css.

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

another flexbox property isorder, as the name suggest it can be used to define where in the flex container the current element should be placed.

for more info on how CSS flex works.
flexbox cheet-sheet

by using this trick we can easy make a simple list which we can sort in any way we want.

Top comments (2)

Collapse
 
kevinhch profile image
Kevin

Pretty good code, but you can use the flex-direction: column-reverse; and some JS to get the same result

Collapse
 
nijeesh4all profile image
Nijeesh Joshy • Edited

Thats a really good point. we can use it to change the direction of the elements we cannot achieve sorting with that approach,
you wont get it sorted properly if the the elements are mixed.

say elements are in the order 1,2,3,4,9,5,10 so if you sorted it with flex-direction: column-reverse; what you will get is 10, 5, 9, 4, 3, 2, 1 its not what we are looking for.