Home > Software engineering >  How to evenly layout dynamic checkboxes
How to evenly layout dynamic checkboxes

Time:04-26

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>

CodePudding user response:

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 >
    <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>

  • Related