CSS Grid min-content不适合内容

时间:2018-05-09 21:54:31

标签: css css3 css-grid

我试图通过向元素显式分配行,列和大小并允许CSS网格使用以下CSS进行列和行大小调整来将一些div放入网格中。

display: grid;
grid-auto-columns: min-content;

min-content应该将列设置为适合内容而没有溢出的最小可能大小。但是,这种情况并没有发生。尽管这些元素都可以放在350px网格中,但第三列太大会导致不必要的空格。

这是一张正在发生的事情的图像。

Image With Gridlines

以下是实际代码:JSFiddle



function randint(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const children = document.getElementById('parent').children;
const skip = 360 / children.length;
let value = randint(0, 359);
for (let i = 0; i < children.length; i += 1) {
  const elm = children[i];
  elm.style.backgroundColor = `hsl(${value}, 100%, 85%)`;
  value += skip;
  elm.id = "w" + (i + 1);
  const style = window.getComputedStyle(elm);
  elm.innerHTML = `width: ${elm.offsetWidth}px<br \>
  col: ${style.getPropertyValue('grid-column')}<br \>
  row: ${style.getPropertyValue('grid-row')}`;
}
&#13;
#parent {
  display: grid;
  grid-auto-columns: min-content;
  border: 1px solid black;
  width: 350px;
  font-size: 10pt;
}

#parent>div {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75px;
}

#w1 {
  width: 200px;
  grid-column: 1 / 3;
  grid-row: 1 / 2;
}

#w2 {
  width: 150px;
  grid-column: 3 / 5;
  grid-row: 1 / 2;
}

#w3 {
  width: 100px;
  grid-column: 1 / 2;
  grid-row: 2 / 3;
}

#w4 {
  width: 150px;
  grid-column: 2 / 4;
  grid-row: 2 / 3;
}

#w5 {
  width: 100px;
  grid-column: 4 / 5;
  grid-row: 2 / 3;
}
&#13;
<div id='parent'>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

第一行中的网格项创建四列:

#w1 {
  width: 200px;
  grid-column: 1 / 3;
  grid-row: 1 / 2;
}

#w2 {
  width: 150px;
  grid-column: 3 / 5;
  grid-row: 1 / 2;
}

第一个项目跨越两列(grid-column: 1 / 3)。

第二项跨越两列(grid-column: 3 / 5)。

所以你有一个4列网格。

在Chrome中,第一行中网格项的长度在列之间平均分配。

所以前两列是100px宽:

enter image description here

第二列是75px宽:

enter image description here

现在您可以看到第二行发生了什么。这是代码:

#w3 {
  width: 100px;
  grid-column: 1 / 2;
  grid-row: 2 / 3;
}

#w4 {
  width: 150px;
  grid-column: 2 / 4;
  grid-row: 2 / 3;
}

#w5 {
  width: 100px;
  grid-column: 4 / 5;
  grid-row: 2 / 3;
}
  • 第一项(#w3)宽度为100px。这非常适合#w1创建的第一列。

  • 第二项(#w4)宽度为150px。 100px非常适合#w1创建的第二列。另一个50px延伸到第三列,由#w2创建,宽度为75px。 留下25px的差距,代表第三列的剩余空间。

  • 第三项(#w5)宽度为100px。但由于它从第四列开始,宽度为75px,剩余的25px溢出容器。

底线: 在Chrome中,一旦呈现第一行,列的宽度就会固定。后续行中的网格项目遵循第一行中建立的列宽。

火狐

与Chrome不同,在Firefox中,似乎在渲染第一行后,列宽不会保持不变。在整个渲染过程中,列宽是灵活的。

enter image description here

边线

与Chrome相同。