Grid布局

133 阅读2分钟

Grid布局总结

页面-容器-容器内划分格子总区域-格子内项目区域-项目

㈠ 容器属性

Ⅰdisplay布局属性

  • display:grid 块状网格 容器是块
  • display:inline-block 行内块网格 容器是行内块

Ⅱ划分行列属性

  • 行 grid-template-rows
  • 列 grid-template-columns
1. 纯数值取值px
grid-template-rows:100px 100px 100px; //每行行高
grid-template-columns:100px 100px 100px; //每列列宽
2. 百分比取值%
  • 容器要设置宽高
grid-template-columns: 20% 30% 50%;
grid-template-rows: 100px 100px 100px;
3. 重复函数取值repeat
  • repeat(重复的次数,重复的值)
  width: 300px;
  height: 300px;
  display: grid;
  grid-template-columns: repeat(3, 100px);
  grid-template-rows: repeat(5, 20%);
  /* 三行五列 每行行高占总高的20% 每列列宽100px */
4. 自动填充取值auto-fill
  • auto-fill 应用在重复函数中,根据需要重复的值,进行自动填充数量
  • g-t-c:repeat(auto-fill,30%)列宽按照容器总宽的30%划分,剩余的10%不再划分
grid-template-columns:repeat(auto-fill,120px);
/* 每行中列的个数不限,列宽120px,列个数自适应 */
5. auto自动
  • 占剩余宽度和剩余高度的所有
  • g-t-c:100px auto 100px中间撑满
6. fr片段划分
  • fraction片段g-t-c:1fr 2fr 3fr子容器完全瓜分,相互之间宽比1:2:3
7. minmax(最小值,最大值)
  • 默认最大值,撑满,最小,保持最小值溢出
  • g-t-c:100px 200px minmax(100px,200px)

Ⅲ gap间距属性

  • 行间距属性:grid-row-gap
  • 列间距属性:grid-column-gap
  • 合并间距属性:grid-gap:行间距 列间距

Ⅳ grid-auto-flow 子项排列方向 : row[default]

  • row[横向显示] column[纵向显示]
  • row 按行排从左到右 行1-行2
  • column 按列排从上到下 列1-列2
  • div.item{$}*9

Ⅴ 子项设置宽高未撑满时对齐方式place-items:align-items justify-items

image.png

  • 默认宽高不设置stretch
  • 默认justify-items:start
  • 子项在容器划分的区域中的对齐方式
  • 水平对齐方式:justify-items
  • 垂直对齐方式:align-items
  • 有宽高 值:start center end 无宽高 stretch
  • 左下 end start

grid容器有剩余,剩余区域对齐方式place-content align-content justify-content

  • start center end
  • stretch 拉伸默认值
  • space-around 行列间距环绕
  • space-between 行列两端对齐
  • space-evenly 行列间距平分

项目属性

合并单元格grid-row grid-column

  • grid-row:grid-row-start/grid-row-end
  • grid-column:grid-column-start/grid-column-end
  • 将划分好的网格,通过让元素使用网格线占位的形式,达到合并的效果

image.png

案例

image.png

/* div.item{$}*42 */
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .grid {
      width: 1700px;
      height: 500px;
      border: 10px solid gray;
      margin: 100px auto;
      display: grid;
      grid-template-rows: repeat(4, 100px);
      grid-template-columns: repeat(13, 100px);
      grid-gap: 10px 10px;
      place-content: center center;
    }

    .item {
      background-color: red;
    }

    .box1 {
      grid-row: 1/3;
      grid-column: 12/14;
    }

    .box2 {
      grid-row: 1/2;
      grid-column: 10/12;
    }

    .box3 {
      grid-row: 2/4;
      grid-column: 6/9;
    }

    .box4 {
      grid-row: 2/3;
      grid-column: 1/3;
    }

    .box5 {
      grid-row: 3/5;
      grid-column: 1/3;
    }

    .box6 {
      grid-row: 4/5;
      grid-column: 12/14;
    }
  </style>