Placing checkboxes based on their checked status

Viewed 55

I'm curious if it's possible to place checkboxes in different areas based on their checked status, with only CSS! I'm a big CSS-only fan when there is a nice comprehensible solution to it.

I obviously put all my hope into grid and flex, but I couldn't come up with a solution which worked as I wanted to.

I hope this image makes my whole problem clear: enter image description here

Active checkboxes in "Area A" and when not active in "Area B". Two Columns.

The HTML would be as simple as:

<div class="options">
    <input type="checkbox" id="checkbox1">
    <label for="checkbox1">checkbox</label>

    <input type="checkbox" id="checkbox2">
    <label for="checkbox2">checkbox</label>

    ...
</div>

It would also be okay when the input and label tag are wrapped. And I can toggle a class on the wrapping tag... (using JS of course)

<div class="options">
    <div class="checked">
        <input type="checkbox" id="checkbox1">
        <label for="checkbox1">checkbox</label>
    </div>

    <div class="">
        <input type="checkbox" id="checkbox2">
        <label for="checkbox2">checkbox</label>
    </div>

    ...
</div>

CSS I tried with this approach:

.options {
    display: grid;
    grid-template-columns: 1fr 1fr;
}

.checked {
    grid-row: 1;
}

But I can't manage to keep them in two columns when more than two boxes are checked.

1 Answers

I did some work to see what i could come up with, sadly i wasn't able to create exactly what you had asked for, but it might be close enough for what you need, or give some creative input :)

https://codepen.io/noex98/pen/OJgVqZr

HTML:

<div class="options">
  <div class="checkWrap">
    <input type="checkbox" id="checkbox1">
    <label for="checkbox1">checkbox 1</label>
  </div>
  <div class="checkWrap">
    <input type="checkbox" id="checkbox2">
    <label for="checkbox2">checkbox 2</label>
  </div>
  <div class="checkWrap">
    <input type="checkbox" id="checkbox3">
    <label for="checkbox3">checkbox 3</label>
  </div>
  <div class="checkWrap">
    <input type="checkbox" id="checkbox4">
    <label for="checkbox4">checkbox 4</label>
  </div>
    <div class="checkWrap">
    <input type="checkbox" id="checkbox5">
    <label for="checkbox5">checkbox 5</label>
  </div>
  <div class="checkWrap">
    <input type="checkbox" id="checkbox6">
    <label for="checkbox6">checkbox 6</label>
  </div>
</div>

CSS:

.options {
    display: flex;
    flex-wrap:wrap; 
}

.checkWrap {
    width:50%;
}

.checkWrap--checked {
    order: -1;
}

JS:

let wrappers = document.querySelectorAll('.checkWrap')
document.querySelector('.options').addEventListener('click', () => {
  for (wrapper of wrappers){
    if (wrapper.getElementsByTagName('input')[0].checked == true){
      wrapper.classList.add('checkWrap--checked')
    } else {
      wrapper.classList.remove('checkWrap--checked')
    }
  }
})
Related