Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to evenly layout dynamic checkboxes

I’m generating a bunch of checkboxes dynamically and am struggling to find a nice way to lay them out. id like to have a set amount of items per row (except the last row where it would just be what is left) all evenly spaced. Can I achieve this with just a bit of css or do I need to change the html structure a bit? since im generating it all dynamically it isnt a problem to create a new div every 4 items for example

https://jsfiddle.net/Elbusta/sLj4ochx/16/

window.onload = function() {
  items = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "aa", "bb", "cc", "ddd", "e", "ff", "g", "boat", "cat", "zion"]

  let html = "";
  let div = document.getElementById("input-wrapper");
  for (i = 0; i < items.length; i++) {
    html += `<input type="checkbox" id="${items[i]}" name="${items[i]}" value="${items[i]}">
    <label for="${items[i]}">${items[i]}</label>`
  }

  div.innerHTML  = html;
}
.input-wrapper {
  text-align: center;
}

input{
  margin: 0px;
}

label{
  margin: 0px 20px 0px 2px;
}
<div id=input-wrapper>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

An option is to use display: flex and flex-wrap

window.onload = function() {
  items = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "aa", "bb", "cc", "ddd", "e", "ff", "g", "boat", "cat", "zion"]

  let html = "";
  let div = document.getElementById("input-wrapper");
  for (i = 0; i < items.length; i++) {
    html += `
    <div class="item">
    <input type="checkbox" id="${items[i]}" name="${items[i]}" value="${items[i]}">
    <label for="${items[i]}">${items[i]}</label>
    </div>`
  }

  div.innerHTML  = html;
}
#input-wrapper {
  display: flex;
  flex-wrap: wrap;
}

input {
  margin: 0px;
}

label {
  margin: 0px 20px 0px 2px;
}
.item {
  width: 15%;
}

@media screen and (max-width: 700px) {
  .item {
    width: 30%;
  }
}
@media screen and (max-width: 400px) {
  .item {
    width: 50%;
  }
}
<div id=input-wrapper>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading