创建具有不同%宽度的新div

问题描述 投票:0回答:3

我用一个div创建了一个部分。每次单击时,“click”按钮都会添加新的div。我需要:div 1 - > 100%宽度(部分)当我点击:div 1和div2(div 2 new) - >每个获得50%宽度。再次单击:div1,div2和div3 - 每个> 30%宽度。再次单击:div 4进入下一行,宽度相同

你有什么主意吗? 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>
javascript css width
3个回答
2
投票

使用这个div风格:

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

“Flex-grow”赋予它们div内部的“重量”,具有相同弹性的项目共享可用空间的相同部分。最小宽度触发第4个div下降,因为将其添加到同一行将使其宽度为25%。

如果您需要任何进一步的解释,请询问!


1
投票

我还建议一些flex-grow和一个条件类来修复3个项目之后的宽度。这是我的尝试;)

我也用过css calc。

(function() {
  const section = document.getElementById('section');

  function addDiv() {
    const div = document.createElement('div');
    div.className = 'new-div';
    section.appendChild(div);

    if (section.childNodes.length > 3) {
      section.classList.add("fixedWith");
    }
  }

  document.getElementById("button").onclick = function() {
    addDiv();
  };

  document.addEventListener("DOMContentLoaded", function() {
    addDiv();
  });
})();
section {
  display: flex;
  height: 100px;
  width: 200px;
  background: red;
  flex-wrap: wrap;
  overflow: auto;
}

div {
  flex-grow: 1;
  min-width: calc(100% / 3 - 4px);
  height: 30px;
  background: blue;
  margin: 5px 2px;
}

section.fixedWith div {
  max-width: calc(100% / 3 - 4px);
}

#button {
  color: red;
}
<html>

<body>
  <button id="button">Click button</button>
  <section id="section"></section>
</body>
<html>

0
投票

将flex:1放在div上表示它将占用其父级的1分之一的空间。当添加另一个div时,它会占用两个可用空间分数中的一个,依此类推。弹性基础:30%;有效地说,每个弹性项目最多可占用该行的可用空间的30%。希望这可以解决您的问题!

section {
  display: flex;
  height: 100px;
  width: 200px;
  background: red;
  flex-wrap: wrap;
  overflow: auto;
}

div {
  display: block;
  height: 10px;
  flex: 1;
  flex-basis: 30%;
  background: blue;
  margin: 5px 2px;
}

#button {
  color: red;
}
© www.soinside.com 2019 - 2024. All rights reserved.