CSS 建立一個三角形
阿新 • • 發佈:2020-10-08
最近面試有被問到如何實現一個三角形,藉此機會總結一下,將常用的幾種方法梳理一遍。
原始檔地址:建立一個三角形
繪製三角形的幾種方法彙總
- transform rotateZ(45deg) + 父子divoverflow:hidden
HTML
<div class='triangle1-wrap'>
<div class='triangle1'></div>
</div>
CSS
.triangle1-wrap{ width:50px; height:50px; overflow:hidden; } .triangle1{ width:50px; height:50px; background-color:red; transform:rotateZ(45deg); margin-top:35px; }
- 設定border
HTML
<div class='triangle2'></div>
CSS
.triangle2{
width:0px;
height:0px;
border-top:solid 50px red;
border-bottom:solid 50px transparent;
border-left:solid 50px transparent;
border-right:solid 50px transparent;
}
- canvas
HTMl
<canvas id='triangle3' width='50' height='50'></canvas>
JS
const triangle = document.getElementById('triangle3'); const ctx = triangle.getContext('2d'); //填充三角形(等邊) ctx.beginPath(); ctx.moveTo(50,0); ctx.lineTo(0,50); ctx.lineTo(50,50); ctx.fillStyle='aqua'; ctx.fill();
- svg
HTML
<svg class='triangle4'>
<path name="三角形" fill="green" d="M50 0 L0 50 L50 50 Z"/>
</svg>
CSS
.triangle4{
width:50px;
}
- 漸變
HTML
<div class="triangle5"></div>
CSS
.triangle5{
width: 50px;
height:50px;
background-image:linear-gradient(45deg,#fff 50%, #2980B9 0);
}
- 偽類
HTML
<div class="triangle6"></div>
CSS
.triangle6{
width:50px;
height:50px;
position: relative;
overflow:hidden;
}
.triangle6:after{
content: "";
width: 50px;
height: 50px;
background-color:brown;
transform: rotate(45deg);
position: absolute;
left: 35px;
top: 0px;
}
- background-image
HTML
<div class="triangle7"></div>
CSS
.triangle7{
width:50px;
height:50px;
background-image:url('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602140892677&di=754062cafde7897f9550b7691882b17b&imgtype=0&src=http%3A%2F%2Ftrademark-pics-search.oss-cn-shanghai.aliyuncs.com%2Fsmall%2Ft4517751695000576.jpg');
background-size:100% 100%;
}
- 字型
HTML
<div class="triangle8">▲</div>
CSS
.triangle8{
font-size:50px;
color:darkmagenta;
}