【问题标题】:How to set custom height of one row in grid?如何设置网格中一行的自定义高度?
【发布时间】:2020-01-06 04:30:33
【问题描述】:

我想在网格图库视图的特定行中设置自定义高度。

.grid-gallery {
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  grid-template-rows: 250px;
  grid-auto-rows: 250px;
  grid-auto-flow: dense;
}

我有 3 列,每行(我有动态的行数)有 250 像素的高度。现在我想添加一个带有.grid-title 类的div,例如100px 的高度,当然这个 div 跨越 3 列以拥有 100% 的网格容器宽度。

我尝试过类似的方法,但它不会改变 3 列的高度。即使使用display: grid,它也不起作用。

.grid-title {
  grid-column: span 3;
  grid-template-rows: 100px;
  grid-auto-rows: 100px;
}

应该是这样的:

编辑

工作笔:

https://codepen.io/freestyle09/pen/oNvGywK

【问题讨论】:

  • 你能添加最少的工作 html 和 css 代码吗?
  • 我已添加问题链接

标签: html css sass


【解决方案1】:

我有 3 列和每一行

如果您有固定数量的列,为什么要将 auto-fit 值设置为 grid-template-columns 属性?

我想添加一个带有 .grid-title 类的 div,例如100像素

如果自定义项总是在一个地方,你可以在grid-template-rows: 250px 250px 100px;加上grid-auto-rows: 250px;中设置这个行高:https://codepen.io/hisbvdis/pen/wvwrXye

如果自定义项目可以在任意位置,您可以设置grid-auto-rows: 100px并为项目添加grid-rows: span 2;属性:https://codepen.io/hisbvdis/pen/vYBerjL

【讨论】:

  • 是的,你是对的,如果我想要 100px 的动态 div 数量呢?我不想手动放置带有标题的 div
  • 我不明白“我不想手动放置带标题的div”是什么意思。我会尝试猜测。像这样的东西? codepen.io/hisbvdis/pen/LYPzrqV?editors=1100
  • 是的,这几乎是完美的,但现在图像的高度是:100 x 2 + 网格间隙,如果我想要 290 像素的图像高度和 50 像素的标题高度怎么办?你知道我想做什么吗?我不想更改图像高度并从行数(跨度 x)计算它,而只想更改具有类标题的 div
  • 如何更改自定义 div 中的自动行高?
【解决方案2】:

好的,我找到了解决方案。当我们想在网格容器内设置几个div的动态高度时,我们必须使用minmax()函数。

grid-auto-rows: minmax(50px,auto);

之后我们可以手动设置网格项的高度:

.item {
    height: 320px;
}

以下是工作示例: https://codepen.io/freestyle09/pen/YzKrjrx

感谢 hisbvdis 为我指出找到答案的方法

【讨论】:

    【解决方案3】:

    将网格容器的网格模板行定义为 50 像素,它是 100 像素(网格标题类)和 250 像素(您需要的默认行大小)的倍数。正如我们定义的那样,每一行的高度为 50 像素。现在,我们可以用 span 2(即 50px * 2)或 span 5(即 50px * 5)覆盖独立类,这将为这些类提供 100 px 和 250 px 的高度。检查我下面的 CSS 属性,这将满足您的条件。

    .grid-gallery {
      max-width: 1000px;
      display: grid;
      grid-gap: 5px;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      grid-template-rows: 50px;
      grid-auto-rows: 50px;
      grid-auto-flow: dense;
    }
    
    .grid-gallery > div{
      background-color: red;
    }
    
    .grid-gallery .grid-title {
      background-color: yellow;
      grid-column: span 3;
      grid-row: span 2;
    /*  Here some rules  */
    }
    .image-gallery {
      grid-row: span 5;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-03
      • 2020-09-22
      相关资源
      最近更新 更多