CSS 三角形 Mixin

Avatar of Kitty Giraudel
Kitty Giraudel

有一个相当流行的 CSS 技巧,它使用透明边框在宽度/高度为 0 的元素上模拟三角形。这里有一个 CSS 代码片段 在 CSS-Tricks 上展示了它。

如果,像我一样,你总是记不住它是如何工作的,请确保我们可以使用 Sass 来帮助我们。

/// Triangle helper mixin
/// @param {Direction} $direction - Triangle direction, either `top`, `right`, `bottom` or `left`
/// @param {Color} $color [currentcolor] - Triangle color 
/// @param {Length} $size [1em] - Triangle size
@mixin triangle($direction, $color: currentcolor, $size: 1em) {
  @if not index(top right bottom left, $direction) {
    @error "Direction must be either `top`, `right`, `bottom` or `left`.";
  }

  width: 0;
  height: 0;
  content: '';
  z-index: 2;
  border-#{opposite-position($direction)}: ($size * 1.5) solid $color;
  
  $perpendicular-borders: $size solid transparent;
  
  @if $direction == top or $direction == bottom {
    border-left:   $perpendicular-borders;
    border-right:  $perpendicular-borders;
  } @else if $direction == right or $direction == left {
    border-bottom: $perpendicular-borders;
    border-top:    $perpendicular-borders;
  }
}

其他说明

* opposite-position 函数 来自 Compass;如果你不使用 Compass,你可能需要 自己实现一个
* Mixin 不处理三角形的位置;不过,完全可以将其与 定位 Mixin 组合使用;
* content 指令旨在允许它用于伪元素,实际上这才是大多数情况。

用法

.foo::before {
  @include triangle(bottom);
  position: absolute;
  left: 50%;
  bottom: 100%;
}
.foo::before {
  width: 0;
  height: 0;
  content: '';
  z-index: 2;
  border-top: 1.5em solid currentColor;
  border-left: 1em solid transparent;
  border-right: 1em solid transparent;
  position: absolute;
  left: 50%;
  bottom: 100%;
}