助力软件开发企业降本增效 PHP / java源码系统,只需一次付费,代码终身使用! 广告
# 7. 对齐单元格/区域中所有项目 [toc] ## 7.1 属性 | 序号 | 属性 | 描述 | | ---- | --------------- | ------------------------------------------------- | | 1 | `justify-items` | 设置所有项目在单元格/网格区域中水平方向的对齐方式 | | 2 | `align-items` | 设置所有项目在单元格/网格区域中垂直方向的对齐方式 | | 3 | `place-items` | 简写, `place-items: 垂直对齐方式 水平对齐方式` | --- ## 7.2 示例 1: 对齐单元格中所有项目 ![](https://img.kancloud.cn/58/cc/58cc3691a6e0905309bbda00fd24aecf_1182x1216.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; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); /* 项目在单元格的对齐方式,默认是拉伸,除非设置了项目大小,否则会占据单元格全部空间 */ justify-items: stretch; align-items: stretch; /* 水平居左,垂直居中 */ justify-items: start; align-items: center; /* 水平居右, 垂直居下 */ justify-items: end; align-items: end; /* 水平垂直居中 */ justify-items: center; align-items: center; /* 这二个属性与flex弹性布局中的属性相同,为了区别, 建议使用简写语法 */ /* 简写语法: place-items: 垂直对齐 水平对齐 */ /* 垂直靠上,水平居右 */ place-items: start end; /* 垂直靠下, 水平居左 */ place-items: end start; /* 垂直居中, 水平居中 */ place-items: center center; /* 二个值一样,同样可以简写成一个值 */ place-items: center; } .item { width: 50px; height: 50px; background-color: violet; font-size: 2rem; } </style> </head> <body> <div class="container"> <span class="item item1">1</span> <span class="item item2">2</span> <span class="item item3">3</span> <span class="item item4">4</span> <span class="item item5">5</span> <span class="item item6">6</span> <span class="item item7">7</span> <span class="item item8">8</span> <span class="item item9">9</span> </div> </body> </html> ``` --- ## 7.3 示例 2: 对齐网格区域中所有项目 ![](https://img.kancloud.cn/7d/2a/7d2a72f33a59177e80d39ac12b7f8092_1214x1260.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; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); /* 所有项目在网格区域中垂直水平对齐 */ place-items: center; } .item { width: 50px; height: 50px; background-color: violet; font-size: 2rem; } .item1 { /* 跨3行,占据最左一列 */ grid-row-end: span 3; } .item2 { background-color: lightskyblue; /* 水平跨2行,垂直跨2列,占据一块四个单元格组成的矩形网格区域 */ grid-row-end: span 2; grid-column-end: span 2; } </style> </head> <body> <div class="container"> <span class="item item1">1</span> <span class="item item2">2</span> </div> </body> </html> ```