如何防止元素用 DOM 换行

How to Prevent Elements from Wrapping with DOM

我似乎无法阻止这些块环绕。对于小于 50 的输入,网格似乎工作正常。

这是我的HTML,但没有太多,甚至尝试了内联空格属性。 CSS,我已经将其设为父级 div,它似乎适用于颜色,但不适用于关闭包装。

如何让方框的行继续?

enter image description here

let makeGrid = function(numberOfRows) {
  let y = 0;
  let x = 0;

  while (y < numberOfRows) {
    x = 0;

    let makeBox = function(_parentBox, _sizeOfBox) {
      let box = document.createElement('div');
      document.body.appendChild(box);
      box.style.width = '28px';
      box.style.height = '28px';
      box.style.border = '1px solid white';
      box.style.display = 'inline-block';
      return box;
    };

    let makeRowBox = function(parentBox) {
      let box = document.createElement('div');
      parentBox.appendChild(box);
      //box.style.border = '1px solid black';
      return box;
    };

    rowBox = makeRowBox(document.body);

    while (x < numberOfRows) {
      makeBox(rowBox, 400);
      x = x + 1;
    }

    y = y + 1;
  }
};

makeGrid(50);
div {
  background-color: rgb(68, 157, 230);
  white-space: nowrap;
  overflow: hidden;
}

div>div {
  display: inline-block;
  border: 2px solid white;
  border: '1px solid black';
  margin-right: 4px;
}
<div style="white-space: nowrap;"></div>

您可以使用 display: inline-flex 设置 boxRows 的样式,这样行将展开以适合其内容。

我删除了在 javascript 中设置的所有内联 CSS。相反,我在框中添加了一个 class。

您还将所有蓝色框添加到 body 而不是 .row (rowBox)。

我需要 floatclear 的组合来制作更小的网格换行符。

let makeGrid = function(numberOfRows) {
  let y = 0;
  let x = 0;

  while (y < numberOfRows) {
    x = 0;

    let makeBox = function(_parentBox) {
      let box = document.createElement('div');
      box.classList.add("box");

      //document.body.appendChild(box);

      _parentBox.appendChild(box); /* added */
      
      //return box;
    };

    let makeRowBox = function(parentBox) {
      let box = document.createElement('div');
      box.classList.add("row");
      
      parentBox.appendChild(box);
      
      return box;
    };

    rowBox = makeRowBox(document.body);

    while (x < numberOfRows) {
      makeBox(rowBox, 400);
      x = x + 1;
    }

    y = y + 1;
  }
};

makeGrid(30);
.row {
  display: inline-flex;
  border: 1px solid black;
  clear: both;
  float: left;
}

.box {
  --box-spacing: 2px;

  width: 28px;
  height: 28px;
  background-color: rgb(68, 157, 230);
  border: var(--box-spacing) solid white;
  flex-basis: 100%;
}