Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox order + CSS counters

Is it possible to use CSS counter in combination with flexbox order style? I want achieve an effect when counter number is the same like element order.

Counters update when some of elements have "display: none" property so I thought that maybe it works also with flexbox order.

   ol {
      list-style: none;
      display: flex;
      counter-reset: section;
    }
    
    li {
      width: 50px;
      height: 50px;
    }
    
    li::before {
      counter-increment: section;
      content: counter(section);
    }
 
 <ol>
      <li style="background-color: wheat; order: 2"></li> <!-- should display 2 -->
      <li style="background-color: olive; order: 3"></li> <!-- should display 3 -->
      <li style="background-color: purple; order: 1"></li> <!-- should sisplay 1 -->
 </ol>

 

https://jsfiddle.net/esx9j0hm/9/

like image 275
chudy91 Avatar asked Sep 16 '25 12:09

chudy91


1 Answers

After reading this MDN article I figured that you can't show css property values in content, but there's a couple of ways to do this.

1. Use data-attributes

Add data-attributes to li elements and show them in content:

ol {
  list-style: none;
  display: flex;
}

li {
  width: 50px;
  height: 50px;
}

li::before {
  content: attr(data-order);
}
<ol>
  <li style="background-color: wheat; order: 2" data-order="2"></li> <!-- should display 2 -->
  <li style="background-color: olive; order: 3" data-order="3"></li> <!-- should display 3 -->
  <li style="background-color: lightblue; order: 1" data-order="1"></li> <!-- should sisplay 1 -->
</ol>

2. Use JS

Use js to get style of li element and set it's content accordingly:

let elements = document.querySelectorAll('ol li');
Array.prototype.forEach.call(elements, function(el, i) {
  let order = getComputedStyle(el)['order'];
  el.textContent = order;
});
ol {
  list-style: none;
  display: flex;
}

li {
  width: 50px;
  height: 50px;
}
<ol>
  <li style="background-color: wheat; order: 2"></li> <!-- should display 2 -->
  <li style="background-color: olive; order: 3"></li> <!-- should display 3 -->
  <li style="background-color: lightblue; order: 1"></li> <!-- should sisplay 1 -->
</ol>
like image 81
fen1x Avatar answered Sep 18 '25 08:09

fen1x