在CSS Grid中混合使用固定长度和repeat()函数。

9

我正在尝试使用网格布局来制作一个日历。每个星期的每一天都会有一个标题。我的目标是将标题行(即网格中的第一行)的高度设置为30像素,并使其余的行分配剩余可用空间。

我的日历CSS如下:

.calendar{
    display:grid;
    grid-template-columns:repeat(1,1fr);
    grid-template-rows:30px repeat(auto-fill,1fr);
}

现在,我认为这样做可以完全符合我的要求,但是那个30像素没有效果,而且每一行的高度都相等。是否可能混合使用静态值和repeat()函数?
我意识到我可以只创建两个网格——一个用于标题,一个用于日期——但我很好奇是否有更简洁的方法。
演示在这里:https://codepen.io/anon/pen/yGEaOm

.calendar {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  grid-template-rows: 30px repeat(auto-fill, 1fr);
}


/** Appearance styles that don't affect the layout */
.calendar {
  min-height: 200px;
}
.day {
  border: 1px solid black;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="calendar">
  <div class="day">
    First
  </div>
  <div class="day">
    Second
  </div>
</div>

1个回答

6

简短回答

不是:

grid-template-rows: 30px repeat(auto-fill, 1fr)

试试这个:

grid-template-rows: 30px repeat(auto-fit, minmax(10px, 1fr))

.calendar {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  grid-template-rows: 30px repeat(auto-fit, minmax(10px, 1fr));
  grid-row-gap: 2px;
}

/** Appearance styles that don't affect the layout */
.calendar {
  min-height: 200px;
  padding: 2px;
  border: 1px solid red;
}
.day {
  border: 1px dashed black;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="calendar">
  <div class="day">First</div>
  <div class="day">Second</div>
</div>

说明

在你的代码中注意这个规则:

grid-template-rows: 30px repeat(auto-fill, 1fr)

这个规则是无效的。

enter image description here

因此,浏览器会忽略它,grid-template-rows 会回退到其默认设置:none(这意味着所有行将由grid-auto-rows隐式创建和调整大小,其默认值为auto)。

来自规范:

§ 7.2. 显式轨道大小: grid-template-rowsgrid-template-columns 属性

none 值。

表示此属性不会创建任何显式网格轨道(尽管grid-template-areas仍然可以创建显式网格轨道)。

注意:在没有显式网格的情况下,任何行/列都将被隐式生成,并且它们的大小将由grid-auto-rowsgrid-auto-columns属性确定。

主要问题auto-fill(和auto-fit)无法与内在灵活长度结合使用,例如automin-contentfr

§ 7.2.2.1. Syntax of repeat()

  • 自动重复(auto-fillauto-fit)不能与内在的灵活的尺寸结合使用。

§ 11. Grid Sizing

因此,由于您的规则((auto-fill, 1fr))包含具有灵活尺寸函数(fr)的auto-fill,它将无法工作。

解决方案可能是通过minmax()解决问题。

而不是:

grid-template-rows: 30px repeat(auto-fill, 1fr)

试试这个:

grid-template-rows: 30px repeat(auto-fill, minmax(10px, 1fr))

更多细节:


1
哦,原来问题不是由“30px”和“repeat()”的组合引起的,而是由“auto-fill”和“1fr”的组合引起的。感谢您的答案。 - Quasipickle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接