【问题标题】:how to set a max-height for a css grid row如何为 CSS 网格行设置最大高度
【发布时间】:2022-02-15 06:26:51
【问题描述】:

我正在尝试将 40px 的最大高度设置为 CSS 网格的第二行。
容器的宽度未知,因此它应该是响应式的。
每个盒子的内容也是未知的。

我尝试了grid-template-rows: auto minmax(0, 40px);,但不幸的是,如果不存在第二行,它也会将高度设置为 40px。

有什么办法可以使用grid-template-rows,防止第二行增长到40px

这是一个示例,您可以看到尽管没有网格项,但第二行占用空间:

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
  grid-template-rows: auto minmax(0, 40px);
  grid-auto-rows: 15px;
  overflow: hidden;
  border: 1px solid orange;
  padding: 0;
}

li {
  list-style: none;
  padding: 10px;
  background: black;
  color: white;
}


body {
 width: 650px;
}
<h1><a href="https://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F">Colors</a></h1>

<ul>
  <li>Android green</li>
  <li>Antique brass</li>
  <li>Antique bronze</li>
  <li>Antique fuchsia</li>
  <li>Antique ruby</li>
  <li>Antique white</li>
</ul>

【问题讨论】:

    标签: html css


    【解决方案1】:

    minmax 的当前 grid 实现始终使用较大的值。 (见minmax() defaulting to max

    因此minmax(0, 40px) 将始终导致40px

    【讨论】:

      【解决方案2】:

      您可以使用grid-auto-rows 属性来定义隐式创建的网格行的高度。

      在您的情况下,您会将网格定义为只有一行。然后,您的内容创建的任何其他网格行都将使用grid-auto-rows 属性定义的维度。这样第二行在需要时才会存在。

      编辑:默认情况下只显示一行,但如果需要,还为第二行定义 40px 的高度,AND 如果需要,为第三、第四、第五行定义 15px 的高度,您可以向grid-auto-rows 添加多个值。

      ul {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(95px, 1fr));
        grid-template-rows: auto;
        grid-auto-rows: 40px 15px 15px 15px;
        overflow: hidden;
        border: 1px solid orange;
        padding: 0;
      }
      li {
        list-style: none;
        padding: 10px;
        background: black;
        color: white;
      }
      body {
       width: 650px;
      }
      <h1><a href="https://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F">Colors</a></h1>
      
      <ul>
        <li>Android green</li>
        <li>Antique brass</li>
        <li>Antique bronze</li>
        <li>Antique fuchsia</li>
        <li>Antique ruby</li>
        <li>Antique white</li>
      </ul>

      【讨论】:

      • 不知道为什么这个答案被否决,但这对我没有帮助,因为它不仅会为第二行设置样式
      • @jantimon 听起来你只打算有两行。我也不确定为什么这被否决了。
      • @jantimon 第 3 行、第 4 行等应该是什么大小?
      • 所有其他行的高度应为0
      • @jantimon 我已将问题编辑为具有自动第一行、40px 第二行(如果需要)、15px 后续行(如果需要)。
      猜你喜欢
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 2023-03-23
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多