Search code examples
cssflexboxcss-selectorscss-variables

Reorder flexbox with pure css


I'd like to encode different orders into css variables in the flex-items style, and then switch the encoded order using the :checked psudo-class.

However, I don't know how to get around the scoping problems. Can someone fix this for me.

.expandable {
  order: var(--oldest);
  background-color:lightblue;
}

#expand-toggle:checked ~ * .expandable {
  order: var(--newest);
  background-color:darkseagreen;
}
<input type="checkbox" id="expand-toggle" />

<div style="display: flex; flex-direction: column">
  <div class="expandable" style="--newest: 1; --oldest: 4; order: var(--oldest);" >A</div>
  <div class="expandable" style="--newest: 2; --oldest: 3; order: var(--oldest);" >B</div>
  <div class="expandable" style="--newest: 3; --oldest: 2; order: var(--oldest);" >C</div>
  <div class="expandable" style="--newest: 4; --oldest: 1; order: var(--oldest);" >D</div>
</div>

I imagine its possible to do order: calc(b*var(--oldest) + (1-b)*var(--newest)) but this seems like a hack.


Solution

  • .expandable {
      order: var(--oldest);
      background-color:lightblue;
    }
    
    #expand-toggle:checked ~ * .expandable {
      order: var(--newest);
      background-color:darkseagreen;
    }
    <input type="checkbox" id="expand-toggle" />
    
    <div style="display: flex; flex-direction: column">
      <div class="expandable" style="--newest: 1; --oldest: 4;" >A</div>
      <div class="expandable" style="--newest: 2; --oldest: 3;" >B</div>
      <div class="expandable" style="--newest: 3; --oldest: 2;" >C</div>
      <div class="expandable" style="--newest: 4; --oldest: 1;" >D</div>
    </div>