目录

使用栅格布局,span和offset的具体数值对应关系

问题现象

栅格布局中span和offset的对应关系是怎么样的,以设置span:8,offset:3为例进行说明。

背景知识

解决方案

已知默认列数为12,span为占用列数,offset为距离前一个的列数,以span:8,offset:3为例可知:

代码示例如下:
@Entry
@Component
struct GridRowExample {
  @State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink];
  @State currentBp: string = 'unknown';

  build() {
    Column() {
      GridRow({
        // 默认个数为12
        columns: 12,
        gutter: { x: 5, y: 10 },
        breakpoints: {
          value: ['400vp', '600vp', '800vp'],
          reference: BreakpointsReference.WindowSize
        },
        direction: GridRowDirection.Row
      }) {
        ForEach(this.bgColors, (color: Color) => {
          // 设置span为8,offset为3
          GridCol({ span: 8, offset: 3, order: 0 }) {
            Row().width('100%').height('20vp');
          }.borderColor(color).borderWidth(2);
        });
      }.width('100%').height('100%')
      .onBreakpointChange((breakpoint) => {
        this.currentBp = breakpoint;
      });
    }.width('80%').margin({ left: 10, top: 5, bottom: 5 }).height(200)
    .border({ color: '#880606', width: 2 });
  }
}