如何使用css实现一个三角形?

1、使用 border 绘制三角形

使用 border 实现三角形利用了高宽为零的容器及透明的 border 实现。

给一个高宽为零的容器设置不同颜色的 border,

div {
  width: 0px;
  height: 0px;
  margin: auto;
}
.normal {
  border-top: 50px solid yellowgreen;
  border-bottom: 50px solid deeppink;
  border-left: 50px solid bisque;
  border-right: 50px solid chocolate;
}
<div class='normal'></div>

Alt

让任何三边的边框的颜色为 transparent,可以得到各种角度的三角形:

.top {
  border: 50px solid transparent;
  border-bottom: 50px solid deeppink;
}

.left {
  border: 50px solid transparent;
  border-right: 50px solid deeppink;
}

.bottom {
  border: 50px solid transparent;
  border-top: 50px solid deeppink;
}

.right {
  border: 50px solid transparent;
  border-bottom: 50px solid deeppink;
}
<div class='top'></div> 
<div class='left'></div>
<div class='bottom'></div>
<div class='right'></div>

Alt

2、使用 linear-gradient 绘制三角形

我们可以使用线性渐变 linear-gradient 实现三角形。它的原理也非常简单,我们实现一个 45° 的渐变:

div {
  width: 100px;
  height: 100px;
  background: linear-gradient(45deg, deeppink, yellowgreen);
}

Alt
让它的颜色从渐变色变为两种固定的颜色:

div {
  width: 100px;
  height: 100px;
  background: linear-gradient(45deg, deeppink, deeppink 50%, yellowgreen 50%, yellowgreen 100%);
}

Alt
再让其中一个颜色透明即可:

div {
        width: 100px;
        height: 100px;
        background: linear-gradient(45deg,  rgb(255, 20, 147) 50%, rgba(154, 205, 50,0) 50%);
    }

Alt

3.使用 clip-path 绘制三角形

clip-path CSS 属性可以创建一个只有元素的部分区域可以显示的剪切区域。区域内的部分显示,区域外的隐藏。剪切区域是被引用内嵌的 URL 定义的路径或者外部 SVG 的路径。

也就是说,使用 clip-path 可以将一个容器裁剪成任何我们想要的样子。

通过 3 个坐标点,实现一个多边形,多余的空间则会被裁减掉,代码也非常简单:

div {
        width: 100px;
        height: 100px;
        background: deeppink;
        clip-path: polygon(0 0, 100% 0, 0 100%, 0 0);
    }

Alt

4、利用字符绘制三角形

这一种有些独特,就是使用字符表示三角形。

下面列出一些三角形形状的字符的十进制 Unicode 表示码。

◄ : &#9664; 
► : &#9654; 
▼ : &#9660; 
▲ : &#9650;
⊿ : &#8895;
△ : &#9651;
<div>&#9660; </div>
div {
    font-size: 100px;
    color: deeppink;
}

Alt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值