使CSS网格适合最小空间

时间:2019-04-25 10:45:09

标签: html css css3 css-grid

我有这样的东西:

.row {
  width: 300px;
  border: 1px solid black;
  display: flex;
}

.otherstuff {
  flex-grow: 1;
}

.grid {
  display: grid;
  grid-auto-flow: column;
  gap: 10px 10px;
}

.cell {
  border: 1px solid blue;
}
<div class='row'>
  <div class='stuff'>Stuff</div>
  <div class='otherstuff'>
    <div class='grid'>
      <div class='cell'>Cell 1</div>
      <div class='cell'>Cell 2</div>
    </div>
  </div>
</div>

我希望网格仅占用所需的 minimum (最小)空间,而不要扩展。我已经读过this thread,看到grid-template-columnsauto的值是可能的,但是有一种方法可以在不事先知道孩子人数的情况下进行吗?

谢谢。

3 个答案:

答案 0 :(得分:6)

您可以使用grid-auto-columns: min-contentgrid-auto-columns: max-content,此属性将仅影响未设置大小的列。

  

grid-auto-columns CSS属性指定隐式创建的网格列轨道的大小。

.row {
  width: 300px;
  border: 1px solid black;
  display: flex;
}

.otherstuff {
  flex-grow: 1;
}

.grid {
  display: grid;
  grid-auto-flow: column;
  gap: 10px 10px;
  grid-auto-columns: max-content;
}

.cell {
  border: 1px solid blue;
}
<div class='row'>
  <div class='stuff'>Stuff</div>
  <div class='otherstuff'>
    <div class='grid'>
      <div class='cell'>Cell 1</div>
      <div class='cell'>Cell 2</div>
    </div>
  </div>
</div>

答案 1 :(得分:4)

您可以使用inline-grid-参见下面的演示

.row {
  width: 300px;
  border: 1px solid black;
  display: flex;
}

.otherstuff {
  flex-grow: 1;
}

.grid {
  display: inline-grid; /* changed */
  grid-auto-flow: column;
  gap: 10px 10px;
}

.cell {
  border: 1px solid blue;
}
<div class='row'>
  <div class='stuff'>Stuff</div>
  <div class='otherstuff'>
    <div class='grid'>
      <div class='cell'>Cell 1</div>
      <div class='cell'>Cell 2</div>
    </div>
  </div>
</div>

答案 2 :(得分:2)

执行flex-grow: 0类中的otherstuff。见下文:

.row {
  width: 300px;
  border: 1px solid red;
  display: flex;
}

.otherstuff {
  flex-grow: 0;
}

.grid {
  display: grid;
  grid-auto-flow: column;
  gap: 10px 10px;
}

.cell {
  border: 1px solid blue;
}
<div class='row'>
  <div class='stuff'>Stuff</div>
  <div class='otherstuff'>
    <div class='grid'>
      <div class='cell'>Cell 1</div>
      <div class='cell'>Cell 2</div>
    </div>
  </div>
</div>