Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I control the order of HTML elements by class name?

Tags:

html

css

I have several divs with fixed class names:

<div class="type-a"></div>
<div class="type-b"></div>
<div class="type-c"></div>

There can be multiples of these and these divs are not always in order. They are dynamically added.

<div class="type-a"></div>
<div class="type-b"></div>
<div class="type-c"></div>
<div class="type-c"></div>
<div class="type-b"></div>
<div class="type-b"></div>
<div class="type-c"></div>
<div class="type-a"></div>

I want to group all the type-a and type-b divs and show them in front of type-c divs (which can be done by floating type-a & type-b to the right and type-c to the left). Also between type-a and type-b I want to show the type-a divs first. And type-b second.

Without re-arranging the above HTML or using JavaScript, I'm trying to get this output:

[type-a] [type-a] [type-b] [type-b] [type-b] [type-c] [type-c] [type-c]

Is this possible with just CSS?

This is the fiddle with the divs floated left and right. The ordering that needs to happen now is between type-a and type-b.

like image 658
user3607282 Avatar asked Mar 15 '18 08:03

user3607282


2 Answers

You can use flexbox and the order property:

.container>div {
  width: 20px;
  height: 20px;
  background-color: yellow;
}

.container {
  display: inline-flex;
}

.type-a {
  order: 1;
}

.type-b {
  order: 2;
}

.type-c {
  order: 3;
}
<div class="container">
  <div class="type-a">A</div>
  <div class="type-b">B</div>
  <div class="type-c">C</div>
  <div class="type-c">C</div>
  <div class="type-b">B</div>
  <div class="type-b">B</div>
  <div class="type-c">C</div>
  <div class="type-a">A</div>
</div>

Order also works with Grid:

.container>div {
  background-color: yellow;
}

.type-a {
  order: 1;
}

.type-b {
  order: 2;
}

.type-c {
  order: 3;
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, 20px);
  
}
<div class="container">
  <div class="type-a">A</div>
  <div class="type-b">B</div>
  <div class="type-c">C</div>
  <div class="type-c">C</div>
  <div class="type-b">B</div>
  <div class="type-b">B</div>
  <div class="type-c">C</div>
  <div class="type-a">A</div>
</div>
like image 78
sol Avatar answered Nov 12 '22 09:11

sol


use flex display:

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

.type-a {
order:1;
}

.type-b {
order:2;
}

.type-c {
order:3;
}
<div class="container">
<div class="type-a">a</div>
<div class="type-b">b</div>
<div class="type-c">c</div>
<div class="type-c">c</div>
<div class="type-b">b</div>
<div class="type-b">b</div>
<div class="type-c">c</div>
<div class="type-a">a</div>
</div>
like image 33
Ali Ezzat Odeh Avatar answered Nov 12 '22 10:11

Ali Ezzat Odeh