企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 3. 单元格尺寸常用单位 [toc] ## 3.1 单位 | 序号 | 单位 | 描述 | | ---- | --------------------- | ---------------------------------- | | 1 | 固定宽度`px` | 固定大小 | | 2 | 百分比`%` | 以容器大小为依据来计算 | | 3 | 自动计算`auto` | 由浏览器决定长度 | | 4 | 比例`fr` | 将容器空间按比例分配给每一个单元格 | | 5 | 区间`minmax(min,max)` | 设置单元格尺寸变化范围 | --- ## 3.2 重复生成单元格 | 序号 | 函数 | 描述 | | ---- | ------------------- | --------------------------------------------------------- | | 1 | 重复生成`repeat()` | 快速生成相同大小单元格的 | | 2 | 自动填充`auto-fill` | 单元格固定,但容器不确定时,可以让一行/列容纳尽可能多的项目 | --- ## 3.3 示例 ![](https://img.kancloud.cn/5a/d8/5ad8425375fe84e43716295651ea0be1_1284x1202.jpg) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>设置单元格数量与尺寸</title> <style> .container { width: 400px; height: 400px; background-color: wheat; display: grid; /* 1. 固定值 /* 固定三列三行 */ grid-template-columns: 100px 100px 100px; grid-template-rows: 100px 100px 100px; /* 2.百分比 */ grid-template-columns: 20% 30% auto; grid-template-rows: 100px auto 100px; /* 3. 按比例划分: fr */ grid-template-columns: 1fr 2fr 2fr; /* (400-100)/3=100,1fr=100px, 2fr=200px */ grid-template-rows: 1fr 100px 2fr; /* 4. 重复设置: repeat() */ grid-template-columns: repeat(3, 100px); grid-template-rows: repeat(3, 100px); /* 按(50px 100px)分组重复排列 */ grid-template-columns: repeat(2, 50px 100px); grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); /* 5. 弹性设置: minmax() */ /* 最大宽度仅100px,导致容器宽度出现未分配空间 */ grid-template-columns: repeat(3, minmax(50px, 100px)); /* 最小高度150px,导致超出容器高度 */ grid-template-rows: repeat(3, minmax(150px, 1fr)); /* 6. 自动填充: auto-fill */ /* 自动填充,直到填满整个容器, 注意如何使用fr和auto,会自动使用最近设置的值 */ width: auto; grid-template-columns: repeat(auto-fill, 100px); grid-template-rows: repeat(auto-fill, 100px); } .item { background-color: lightblue; font-size: 2rem; } </style> </head> <body> <!-- .container>.item.item$*3{$} --> <div class="container"> <span class="item item1">1</span> <span class="item item2">2</span> <span class="item item3">3</span> <span class="item item3">4</span> <span class="item item3">5</span> <span class="item item3">6</span> <span class="item item3">7</span> </div> </body> </html> ```