clip-pathで三角形を作成する

以前にborderを使った三角形Sassのmixinの記事を投稿しましたが、今回はclip-pathを使った三角形の作成方法と、そのmixin化について試してみます。

サンプルコード

まずはclip-pathで三角形を作ってみます。
clip-pathについては以前に記事を投稿していますので、詳しくはそちらもご確認ください。

<div class="triangle-top"></div>
<div class="triangle-bottom"></div>
<div class="triangle-left"></div>
<div class="triangle-right"></div>

底辺と高さがそれぞれ100pxの三角形を作成します。

.triangle-top,
.triangle-bottom,
.triangle-left,
.triangle-right {
	width: 100px;
	height: 100px;
	background: red;
	margin-block: 20px;
}

.triangle-top {
	clip-path: polygon(
		50% 0%,
		100% 100%,
		0% 100%
	);
}
.triangle-bottom {
	clip-path: polygon(
		50% 100%,
		100% 0%,
		0% 0%
	);
}
.triangle-left {
	clip-path: polygon(
		0% 50%,
		100% 0%,
		100% 100%
	);
}
.triangle-right {
	clip-path: polygon(
		100% 50%,
		0% 0%,
		0% 100%
	);
}

clip-pathの座標の指定を%にして、対象要素の幅高さに合わせて三角形を作成するようにしています。
三角形を作成するデモページ

次にSassのmixinで三角形を作成できるようにしてみます。

// ----------------------------------------
// 三角形の作成
//
// $direction: 三角形の方向(top, bottom, left, right から選択)
// $base: 三角形の底辺
// $height: 三角形の高さ
// $color: 三角形の色
// ----------------------------------------
@mixin triangle($direction, $base, $height, $color) {
  background-color: $color;
  @if $direction == top {
    width: $base;
    height: $height;
    clip-path: polygon(
      50% 0%,
      100% 100%,
      0% 100%
    );
  } @else if $direction == bottom {
    width: $base;
    height: $height;
    clip-path: polygon(
      50% 100%,
      100% 0%,
      0% 0%
    );
  } @else if $direction == left {
    width: $height;
    height: $base;
    clip-path: polygon(
      0% 50%,
      100% 0%,
      100% 100%
    );
  } @else if $direction == right {
    width: $height;
    height: $base;
    clip-path: polygon(
      100% 50%,
      0% 0%,
      0% 100%
    );
  } @else {
    @error "#{$direction}は未定義のdirectionです。top, bottom, left, right から指定してください。";
  }
}

実際に使ってみます。

.test-top {
  @include triangle(top, 10px, 20px, red);
}
.test-bottom {
  @include triangle(bottom, 30px, 40px, blue);
}
.test-left {
  @include triangle(left, 50px, 60px, green);
}
.test-right {
  @include triangle(right, 70px, 80px, yellow);
}

以下のように生成されました。

.test-top {
  background-color: red;
  width: 10px;
  height: 20px;
  clip-path: polygon(50% 0%, 100% 100%, 0% 100%);
}
.test-bottom {
  background-color: blue;
  width: 30px;
  height: 40px;
  clip-path: polygon(50% 100%, 100% 0%, 0% 0%);
}
.test-left {
  background-color: green;
  width: 60px;
  height: 50px;
  clip-path: polygon(0% 50%, 100% 0%, 100% 100%);
}
.test-right {
  background-color: yellow;
  width: 80px;
  height: 70px;
  clip-path: polygon(100% 50%, 0% 0%, 0% 100%);
}
このエントリーをはてなブックマークに追加

関連記事

コメントを残す

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

CAPTCHA


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

2024年9月
1234567
891011121314
15161718192021
22232425262728
2930