浅谈CSS实现各种三角形

625 阅读1分钟

在平时前端开发中,经常会遇到界面设计需要画各种三角形的需求,一般解决方法有两种,第一种就是需要UI设计师设计出相应的三角形图片,直接在代码里面通过Image标签引用,或者是将图片转换图标iconfont再引入代码中。而另外一种方法也是最简单的性能更好的方法就是通过CSS实现各种常见三角形。

1. 实现一个简单的三角形

简单三角形

实现原理:使用CSS盒模型中的border实现,通过设置元素的width:0height:0,增加border宽度去实现

<div class="organe"></div>
.organe {
    width: 0px;
    height: 0px;
    border-right: 50px solid transparent;
    border-left: 50px solid transparent;
    border-bottom: 50px solid orange;
}

2.实现带边框的三角形

实现原理:利用绝对定位position,两个三角形叠放在一起

微信截图_20210417190757.png

<div class="blue"></div>
.blue {
    position: relative;
    width: 0px;
    height: 0px;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 50px solid blue;
}

.blue::after {
    content: "";
    position: absolute;
    top: 1px;
    left: -48px;
    border-right: 48px solid transparent;
    border-left: 48px solid transparent;
    border-bottom: 48px solid orange;
}

3.绘制其它角度的三角形

右直角三角形

微信截图_20210417191252.png

<div class="orange"></div>
.orange {
    width: 0px;
    height: 0px;
    border-left: 50px solid transparent;
    border-bottom: 50px solid orange;
}

三角形箭头

微信截图_20210417222534.png

<div class="blue"></div>
.blue {
    position: relative;
    width: 0px;
    height: 0px;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 50px solid blue;
}

.blue::after {
    content: "";
    position: absolute;
    top: 1px;
    left: -50px;
    border-right: 50px solid transparent;
    border-left: 50px solid transparent;
    border-bottom: 50px solid #F5F5F5;
}