CSS 网格布局API-函数

266 阅读3分钟
  • 本文简单的说一下和网格布局相关的 3 个函数, repeat() minmax() fit-content()

repeat

  • 函数表示轨道列表的重复片段,允许以更紧凑的形式写入大量显示重复模式的列或行
  • 该函数可以用于 CSS Grid 属性中 grid-template-columns 和 grid-template-rows

示例

  • 语法为 grid-template-columns: 1fr 1fr 2fr or grid-template-columns: repeat(2, 1fr) 2fr, 为了方便我们在下面将省略 grid-template-columns:
repeat(3, 1fr);
/* 1fr 1fr 1fr */

repeat(3, [col-start] 60% [col-end]);
/* [col-start] 60% [col-end col-start] 60% [col-end col-start] 60% [col-end]*/

repeat(3, [col-start] min-content [col-end])
repeat(3, [col-start] max-content [col-end])
repeat(3, [col-start] auto [col-end])

repeat(3, [col-start] minmax(100px, 1fr) [col-end])
repeat(3, [col-start] fit-content(200px) [col-end])

repeat(2, 1fr 30px)
/* 1fr 30px 1fr 30px */
  • 上面的例子中加了一些注释, 大部分应该都可以理解
  • fr 单位指定轨道的弹性系数。轨道会根据其弹性系数按比例分配剩余空间
  • max-content 网格轨道的网格项目所分配的最大内容区域的最大值
  • min-content 网格轨道的网格项目所分配的最小内容区域的最小值
  • auto 作为最大值时,等同 max-content; 作为最小值时, 最小尺寸的最大值(如同 min-width/ min-height
repeat(auto-fill, 250px)
repeat(auto-fit, 250px)
  • auto-fill 如果网格容器在相关轴上具有确定的大小或最大大小,则重复次数是最大可能的正整数,不会导致网格溢出其网格容器。如果定义了,将每个轨道视为其最大轨道尺寸大小函数 ( grid-template-rows 或 grid-template-columns用于定义的每个独立值。否则,作为最小轨道尺寸函数,将网格间隙加入计算。如果重复次数过多,那么重复值是 1 。否则,如果网格容器在相关轴上具有确定的最小尺寸,重复次数是满足该最低要求的可能的最小正整数。否则,指定的轨道列表仅重复一次。
  • auto-fit 行为与 auto-fill 相同,除了放置网格项目后,所有空的重复轨道都将折叠。空轨道是指没有流入网格或跨越网格的网格项目。(如果所有轨道都为空,则可能导致所有轨道被折叠。)折叠的轨道被视为具有单个固定轨道大小函数为 0px,两侧的槽都折叠了。为了找到自动重复的轨道数,用户代理将轨道大小限制为用户代理指定的值(例如 1px),以避免被零除。
  • auto-fill 的一个响应是布局示例 juejin.cn/post/727966…

minmax

  • 定义一个长宽范围的闭区间,它与CSS 网格布局一起使用
  • 此函数包含两个参数,最小值 和 最大值

示例

  • 语法为 grid-template-columns: minmax(200px, 1fr) 2fr, 为了方便我们在下面将省略 grid-template-columns:
minmax(200px, 1fr)
minmax(100px, max-content)
minmax(min-content, 400px)
minmax(min-content, auto)
  • x-contentauto 基本上和 repeat 函数中的用法相同
  • max-content 表示网格的轨道长度自适应内容最大的那个单元格。
  • min-content 表示网格的轨道长度自适应内容最小的那个单元格。
  • auto 作为最大值时,等同 max-content; 作为最小值时, 最小尺寸的最大值(如同 min-width/ min-height
  • repeat 的示例一样都有涉及 juejin.cn/post/727966…

fit-content

  • 盒子会使用可用的空间,但永远不会超过 max-content
  • fit-content 属性可以用于设置元素的 widthheightmin-widthmin-heightmax-width 和 max-height,此时最大和最小尺寸将基于元素的内容尺寸计算。

示例

width: fit-content;
block-size: fit-content;
  • 实际上不在网格布局中也可以正常使用

参考文档