You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Sass循环实现4×4网格内元素的偏移布局?

解决方案

首先需要给.holder添加相对定位,确保绝对定位的子元素基于父容器定位,再通过Sass循环计算每个figure的偏移位置:

.holder {
  width: 100%;
  height: 100%;
  position: relative; /* 核心:让子元素以此为定位基准 */
}

figure {
  width: 25%;
  height: 25%;
  position: absolute;
  border: 1px solid #000;
  box-sizing: border-box; /* 避免边框撑大元素,严格保持25%尺寸 */
  margin: 0; /* 清除figure默认外边距 */
}

@for $i from 1 through 12 {
  figure[data-partial="#{$i}"] {
    // 计算列索引(0-3),对应左偏移0%/25%/50%/75%
    $col: ($i - 1) % 4;
    // 计算行索引(0-2),对应上偏移0%/25%/50%
    $row: floor(($i - 1) / 4);
    
    left: $col * 25%;
    top: $row * 25%;
  }
}

关键说明:

  • 你不需要在循环中修改width和height,基础样式里的25%已经满足需求,循环只负责定位每个元素的位置。
  • box-sizing: border-box是必要的,否则边框会让元素实际尺寸超过25%,导致网格错位。
  • HTML结构保持你提供的原样即可,无需调整。

内容的提问来源于stack exchange,提问作者mathias5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:41:14