CSS网格中每行可以有不同数量的列吗? [英] Can I have a varying number of columns per row in a CSS grid?

查看:115
本文介绍了CSS网格中每行可以有不同数量的列吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: 100px;
  grid-auto-rows: 60px;
  grid-gap: 15px;
}

.col {
  background-color: tomato;
}

<div class="grid">
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
</div>

这将创建2行,第一行是100px高度,第二行是使用60px高度自动创建的.第二行的2列具有1fr宽度.

This creates 2 rows, first is 100px height, second is auto-created with 60px height. 2 columns in the second row have 1fr width.

是否可以通过CSS Grid/Flexbox将第二行中的两列水平居中? IE.每行有不同数量的列.

Is this possible via CSS Grid/Flexbox to horizontally center 2 columns in the 2nd row? I.e. have a varying number of columns per row.

我一直在努力解决浏览器中CSS Grid框架的琐碎用例.如果使用Flexbox构建网格,这是很容易实现的.

I am stuck trying to solve a trivial usecase for the CSS Grid framework in the browser. This is pretty nonproblematic to achieve if you build your grids with Flexbox.

但是我可以用CSS Grid实现吗?

But can I achieve it with CSS Grid?

这是我要实现的目标的 CodePen演示.

Here is a CodePen demo of what I am trying to achieve.

推荐答案

如果行中单元的数量不相同,而这些单元不是全部都放在一个二维(行和列)空间中,则没有一个网格.根据定义,网格包含固定数量的行和列,以及跨越一个或多个单元格的单元格.也许您会拥有多个异构网格,每行一个,但是,这确实击败了整个网格.

If your rows have varying numbers of cells that aren't all laid out on a single two-dimensional (row and column) space, you don't have a grid. A grid by definition contains a fixed number of rows and columns, and cells that span one or more of each. Maybe you'd have multiple heterogeneous grids, one per row, but that just defeats the whole point of grids, really.

如果行数的变化是对称的或遵循某种模式,则可以遵循Michael_B的建议,即基于公共分母构建网格并填充网格区域镶嵌样式.这几乎与当前的flexbox解决方案一样重要,但是一旦浏览器实现了

If your varying number of rows is symmetrical or follows some kind of pattern, you can follow Michael_B's suggestion of building a grid based on a common denominator and populating the grid areas mosaic-style. This is just about as non-trivial as a flexbox solution currently would be, but once more browsers implement flexbox fragmentation, flexbox should become the obvious choice over grid as it ought to be.

这篇关于CSS网格中每行可以有不同数量的列吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆