直接用 aspect-ratio 即可,无需 SCSS 封装;仅当需兼容旧版 Safari 时,才需通过 @mixin square 处理降级逻辑。

直接用 aspect-ratio 就别封装了
如果项目只支持 Chrome 88+、Firefox 89+、Safari 15.4+,aspect-ratio: 1 / 1 一行搞定,根本不需要 SCSS 封装。加个 width: 100% 或 max-width 控制自适应宽度即可,高度自动跟随。强行封装反而增加维护成本,且掩盖了浏览器兼容性这个真实约束。
@mixin square 必须处理降级逻辑
真正需要封装的场景,是必须兼容旧版 Safari(padding-bottom: 100% + height: 0 方案,但不能简单把样式堆进去——SCSS mixin 要负责把现代写法和降级写法都输出,且顺序不能错:
- 现代属性(
aspect-ratio)必须写在降级规则之后,否则会被覆盖 - 降级部分要确保父容器有明确宽度(比如
width: 100%),否则padding-bottom: 100%无意义 - 内容区需配合
position: absolute填充,否则会被 padding 推下去;这不属于 mixin 职责,但文档里得提醒
示例写法:
@mixin square {
width: 100%;
height: 0;
padding-bottom: 100%;
position: relative;
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
// 现代写法后置,覆盖降级
aspect-ratio: 1 / 1;
height: auto;
padding-bottom: 0;
}
传参设计要避开单位混杂
别让使用者传 100vw 或 50% 这类带单位的值进 mixin——SCSS 插值容易出错,且无法做单位校验。真正该暴露的参数只有两个:
立即学习“前端免费学习笔记(深入)”;
-
$ratio:纯数字比值,如1(正方形)、4/3(宽屏图) -
$width:可选,用于控制基础宽度,类型限定为length(如100%、20rem),避免传字符串
这样既保证编译安全,又留出扩展性。例如:
@mixin square($ratio: 1, $width: 100%) {
width: $width;
height: 0;
padding-bottom: percentage($ratio);
position: relative;
aspect-ratio: #{$ratio} / 1;
height: auto;
padding-bottom: 0;
}
别忘了 overflow: hidden 和 BFC 陷阱
用 padding-bottom 撑高的容器,若内部有 max-height 或需要精确截断内容,会失效——因为 max-height 只限制 content height,而高度实际来自 padding。这时候必须触发 BFC:
- 加
overflow: hidden是最轻量方案,但会裁剪溢出内容 - 若需保留滚动或阴影效果,得换伪元素 +
margin-top+overflow: hidden组合,结构更重 - SCSS mixin 里不建议默认加
overflow: hidden,它属于业务逻辑决策,应在调用处显式声明
真正容易被忽略的是:当正方形内嵌图片或文字时,font-size、line-height、border 都可能破坏比例——这些不在 mixin 范围内,但得提醒使用者自查 box-sizing 和内边距影响。


















