CSS网格:如何将所有内容放在一行中?

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

我正在尝试更多地使用网格,但是我无法解决应该是一个简单的问题。如何将所有元素放在一行中?

即,我想模拟单行的flex布局。

我知道我可以在下面的示例中使用grid-template-columns: 1fr 1fr 1fr 1fr;,但我不想设置特定的列数。

div#flex {
  display: flex;
  flex-direction: row; /* I know that’s not necessary */
}
div#flex>button {
  flex: 1;
}

div#grid {
  display: grid;
  grid-template-rows: 1fr;
}
div#grid>button {

}
<div id="flex">
  <button>One</button>
  <button>Two</button>
  <button>Three</button>
  <button>Four</button>
</div>

<div id="grid">
  <button>One</button>
  <button>Two</button>
  <button>Three</button>
  <button>Four</button>
</div>
css flexbox css-grid
1个回答
0
投票

您可以只添加grid-auto-flow: column;https://stackblitz.com/edit/angular-9midxc

CSS:

div#flex {
  display: flex;
  flex-direction: row; /* I know that’s not necessary */
}
div#flex>button {
  flex: 1;
}

div#grid {
  display: grid;
   grid-auto-flow: column; 
}
div#grid>button {

}

HTML:

<div id="flex">
  <button>One</button>
  <button>Two</button>
  <button>Three</button>
  <button>Four</button>
</div>

<div id="grid">
  <button>One</button>
  <button>Two</button>
  <button>Three</button>
  <button>Four</button>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.