Sassで三角形を作るmixinを作成する

以前にCSSで三角形を作る記事を投稿しましたが、疑似要素で三角形を作る機会が度々あるので、Sassのmixinで作成できるようにしてみます。

サンプルコード

まずはmixin部分です。
三角形の方向と底辺、高さ、色を指定できるようにします。

@use "sass:math";
// $direction: 三角形の方向(top, bottom, left, right から選択)
// $base: 三角形の底辺
// $height: 三角形の高さ
// $color: 三角形の色
@mixin triangle($direction, $base, $height, $color) {
  width: 0;
  height: 0;
  border: transparent math.div($base, 2) solid;
  @if $direction == top {
    border-bottom-color: $color;
    border-bottom-width: $height;
  } @else if $direction == bottom {
    border-top-color: $color;
    border-top-width: $height;
  } @else if $direction == left {
    border-right-color: $color;
    border-right-width: $height;
  } @else if $direction == right {
    border-left-color: $color;
    border-left-width: $height;
  } @else {
    @error "#{$direction}は未定義のdirectionです。top, bottom, left, right から指定してください。";
  }
}

三角形の実装自体は以前投稿した記事と同じなので、仕組みに関してはそちらを参照ください。

実際にmixinを使ってみます。

<div class="arrow arrow-top">吹き出しテキスト<br />上向き三角形</div>
<div class="arrow arrow-bottom">吹き出しテキスト<br />下向き三角形</div>
<div class="arrow arrow-left">吹き出しテキスト<br />左向き三角形</div>
<div class="arrow arrow-right">吹き出しテキスト<br />右向き三角形</div>
.arrow {
  position: relative;
  width: 250px;
  margin: 20px auto;
  border-radius: 5px;
  border: #3498DB 2px solid;
  padding: 5px;
}
.arrow:after {
  content: '';
  display: block;
  position: absolute;
}
.arrow-top:after {
  top: -18px;
  left: 10px;
  @include triangle(top, 16px, 8px, #3498DB);
}
.arrow-bottom:after {
  bottom: -17px;
  right: 10px;
  @include triangle(bottom, 10px, 10px, #3498DB);
}
.arrow-left:after {
  top: 10px;
  left: -28px;
  @include triangle(left, 12px, 20px, #3498DB);
}
.arrow-right:after {
  bottom: 10px;
  right: -22px;
  @include triangle(right, 20px, 10px, #3498DB);
}

三角形のデモページ

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930