Search code examples
javascriptcsswidth

Create new div with different %width


I've created a section with one div. The button 'click' adds new div each time when I click. What I need: div 1 -> 100% width (section) when I click: div 1 and div2 (div 2 new) -> get 50% width each. click again: div1, div2 and div3 -> 30% width each. click again: div 4 goes to next line with the same width

Do you have any idea? https://jsfiddle.net/Vova_Champion/tcyw64wq/6/

document.getElementById("button").onclick = function() {
  let ok = true;
  if (ok === true) {
    let div = document.createElement('div');
    div.className = 'new-div';

    document.getElementsByTagName('section')[0].appendChild(div);
  }
};
section {
  display: flex;
  height: 100px;
  width: 200px;
  background: red;
  flex-wrap: wrap;
  overflow: auto;
}

div {
  display: block;
  height: 30px;
  width: 100%;
  max-width: 30%;
  background: blue;
  margin: 5px 2px;
}

#button {
  color: red
}
<button id="button">Click button</button>
<section id="section">
  <div></div>
</section>


Solution

  • Use this div style:

    div {
      flex-grow: 1;
      display:block;
      height: 30px;
      min-width: 30%;
      background: blue;
      margin: 5px 2px;
    }
    

    "Flex-grow" gives them "weight" inside the div, items with the same flex grow share the same portion of the available space. Min-width triggers the 4th div to go down since adding that to the same line would make their width 25%.

    If you need any further explanation, please ask!