当我调整窗口大小时,如何防止所有flex项目调整大小?

时间:2018-02-23 22:00:51

标签: javascript html css css3 flexbox

我在我的flex-container上尝试使用以下单击我的按钮来生成内容,但是当我调整窗口大小时,它会不断调整我的项目大小。我希望它们具有固定的宽度和高度(理想情况下每个项目将是100x100像素的正方形)

flex-shrink: 0;
flex-grow: 0;

const sampleContent = ["stuff1", "stuff2", "stuff3", "stuff4", "stuff5"]
const button = document.querySelector(".content");
const rootElement = document.querySelector("#root");
const widthDiv = document.querySelector("#width-value");
const resultContainer = document.querySelector("#root");
const widthValue = window.getComputedStyle(resultContainer, null).getPropertyValue("width");
button.addEventListener("click", () => {
	sampleContent.forEach((content) => {
  const newDiv = document.createElement("div");
  console.log(newDiv);
  newDiv.textContent = content;
  newDiv.classList.add("result");
  rootElement.appendChild(newDiv);
  })
})
widthDiv.textContent = widthValue;
.result-container {
  display: flex;
  width: 60%;
  height: 200px;
  border: 1px black solid;
  flex-wrap: nowrap;
}
.container {
  display: flex;
  justify-content: center;
}
.result {
  width: 100px;
  height: 100px;
  border: 1px dotted pink;
  margin: 1%;
}
<div class="container">
  <div id="root" class="result-container">
  
  </div>
</div>

  <button class="content">
    Generate Content from API
  </button>
  <div id="width-value">
  </div>

1 个答案:

答案 0 :(得分:1)

弹性项目的初始设置为flex-shrink: 1。这意味着物品可以收缩以避免容器溢出。将flex-shrink: 0添加到商品中即可完成设置。

const sampleContent = ["stuff1", "stuff2", "stuff3", "stuff4", "stuff5"]
const button = document.querySelector(".content");
const rootElement = document.querySelector("#root");
const widthDiv = document.querySelector("#width-value");
const resultContainer = document.querySelector("#root");
const widthValue = window.getComputedStyle(resultContainer, null).getPropertyValue("width");
button.addEventListener("click", () => {
  sampleContent.forEach((content) => {
    const newDiv = document.createElement("div");
    console.log(newDiv);
    newDiv.textContent = content;
    newDiv.classList.add("result");
    rootElement.appendChild(newDiv);
  })
})
widthDiv.textContent = widthValue;
.result-container {
  display: flex;
  width: 60%;
  height: 200px;
  border: 1px black solid;
  flex-wrap: nowrap;
}

.container {
  display: flex;
  justify-content: center;
}

.result {
  flex: 0 0 100px;
  /* fg: 0, fs: 0, fb: 100px */
  /* width: 100px; */
  height: 100px;
  border: 1px dotted pink;
  margin: 1%;
}
<div class="container">
  <div id="root" class="result-container"></div>
</div>
<button class="content">Generate Content from API</button>
<div id="width-value"></div>