CSSのborderで三角形を作るSassのmixin


要約

  • コーディングでよく使う三角形をCSSのborderプロパティで作ります
  • Sassのmixinなので、いろいろなサイトで流用できます
  • 上下左右と右上・右下・左下・左上の8パターンが生成できます
  • 正三角形と二等辺三角形に対応していて、(3つの辺の長さがすべて違う)不等辺三角形は対応していません
  • 三角形のジェネレーターであるCSS三角形作成ツールCSS Triangle Generatorと同じようなことができます

コード

// @desc  ボーダーで三角形を作ります。
// @param {String} $width
// @param {String} $height
// @param {String} $direction [right]
// @param {String} $color [currentColor]
// @example scss - Usage
// .triangle {
//   &:before {
//     content: "";
//     display: block;
//     @include triangle(10px, 15px, top);
//   }
// }
// @example css - CSS output
// .triangle:before {
//   content: "";
//   display: block;
//   width: 0;
//   height: 0;
//   border-style: solid;
//   border-color: transparent transparent currentColor transparent;
//   border-width: 0 5px 15px 5px;
// }
@mixin triangle($width, $height, $direction: right, $color: currentColor) {
  @if not index(top right bottom left top-right bottom-right bottom-left top-left, $direction) {
    @warn "$direction must be one of `top`, `right`, `bottom`, `left`, `top-right`, `bottom-right`, `bottom-left`, `top-left`; currently `#{$direction}`.";
  }

  width: 0;
  height: 0;
  border-style: solid;

  @if $direction == top {
    border-color: transparent transparent $color transparent;
    border-width: 0 ($width / 2) $height ($width / 2);
  }

  @if $direction == right {
    border-color: transparent transparent transparent $color;
    border-width: ($height / 2) 0 ($height / 2) $width;
  }

  @if $direction == bottom {
    border-color: $color transparent transparent transparent;
    border-width: $height ($width / 2) 0 ($width / 2);
  }

  @if $direction == left {
    border-color: transparent $color transparent transparent;
    border-width: ($height / 2) $width ($height / 2) 0;
  }

  @if $direction == top-right {
    border-color: transparent $color transparent transparent;
    border-width: 0 $height $height 0;
  }

  @if $direction == bottom-right {
    border-color: transparent transparent $color transparent;
    border-width: 0 0 $height $height;
  }

  @if $direction == bottom-left {
    border-color: transparent transparent transparent $color;
    border-width: $height 0 0 $height;
  }

  @if $direction == top-left {
    border-color: $color transparent transparent transparent;
    border-width: $height $height 0 0;
  }
}

使い方

横幅・高さ・向き(ここでは上向き)・色を指定できます。
省略すると向きは右向きに、色はcurrentColorでその要素のcolorプロパティを継承します。

// Sassの指定例
.triangle {
  &:before {
    content: "";
    display: block;
    @include triangle(10px, 15px, top, #000);
  }
}
// CSSの出力例
.triangle:before {
  content: "";
  display: block;
  width: 0;
  height: 0;
  border-style: solid;
  border-color: transparent transparent #000 transparent;
  border-width: 0 5px 15px 5px;
}