用于偏移定位的 Mixin

Avatar of Kitty Giraudel
Kitty Giraudel

如果说有一种 CSS 简写方式非常缺乏,那就是同时定义 `position` 属性以及四个偏移属性(`top`、`right`、`bottom`、`left`)的简写方式。

幸运的是,这通常可以通过 CSS 预处理器(如 Sass)来解决。我们只需要构建一个简单的 mixin 就可以避免手动声明这 5 个属性。

/// Shorthand mixin for offset positioning
/// @param {String} $position - Either `relative`, `absolute` or `fixed`
/// @param {Length} $top [null] - Top offset
/// @param {Length} $right [null] - Right offset
/// @param {Length} $bottom [null] - Bottom offset
/// @param {Length} $left [null] - Left offset
@mixin position($position, $top: null, $right: null, $bottom: null, $left: null) {
  position: $position;
  top: $top;
  right: $right;
  bottom: $bottom;
  left: $left;
}

现在的问题是,我们在使用此 mixin 时依赖于命名参数,以避免在只需要一两个参数时必须设置所有参数。请考虑以下代码

.foo {
  @include position(absolute, $top: 1em, $left: 50%);
}

…它编译成

.foo {
  position: absolute;
  top: 1em;
  left: 50%;
}

实际上,Sass 永远不会输出值为 `null` 的属性。

简化 API

我们可以将位置类型移动到 mixin 名称中,而不是将其定义为第一个参数。为此,我们需要另外三个 mixin 作为我们刚刚定义的 `position` mixin 的别名。

/// Shorthand mixin for absolute positioning
/// Serves as an alias for `position(absolute, ...)`
/// @param {Arglist} $args - Offsets
/// @require {mixin} position
@mixin absolute($args...) {
  @include position(absolute, $args...);
}

/// Shorthand mixin for relative positioning
/// Serves as an alias for `position(relative, ...)`
/// @param {Arglist} $args - Offsets
/// @require {mixin} position
@mixin relative($args...) {
  @include position(relative, $args...);
}

/// Shorthand mixin for fixed positioning
/// Serves as an alias for `position(fixed, ...)`
/// @param {Arglist} $args - Offsets
/// @require {mixin} position
@mixin fixed($args...) {
  @include position(fixed, $args...);
}

重写我们之前的示例

.foo {
  @include absolute($top: 1em, $left: 50%);
}