携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情
之前工作有个画菱形的需求,结果发现不会画菱形。搜了网上方法虽然解决了,但就想找个空闲日子看三角形能用几个css方法画出来。
首先最基本的transparent很容易
方法一:transparent
利用border中的transparent方法来改变,border宽度和border底部宽度设置为一样
- 缺点:没了宽度会根据屏幕尺寸来变得很大,但是有了宽度的话,就会变成梯形
<style>
.triangle{
border: 450px solid transparent;
//1. border-bottom: 450px solid yellow;
border-color: transparent transparent yellow transparent ; //2.
}
</style>
<body>
<div class="triangle"></div>
</body>
方法二: clip-path: polygon()
css中的clip-path属性,就是有点绕并且不能设置边框
<style>
.triangle{
width: 150px;
height: 150px;
background-color: yellow;
//第一个xy以头部顶点为xy轴变
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
</style>
<body>
<div class="triangle"></div>
</body>
方法三: canvas
<canvas id = 'canvas'></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath(); //新建路径开始绘制
ctx.moveTo(75, 0); //起始点
ctx.lineTo(0, 150); //移动位置
ctx.lineTo(150, 150);
ctx.fillStyle = "yellow";
ctx.fill(); //通过填充路径的内容区域生成实心的图形
</script>
- 上面三种各种三角形状都可以,下面只能非等腰三角形
方法四: background: linear-gradient()
<style>
.triangle{
width: 150px;
height: 150px;
//左下↙为起点,yellow画到50%,透明从50%画到100%
background: linear-gradient(45deg,yellow,yellow 50%,transparent 50%,transparent 100%);
}
</style>
</head>
<body>
<div class="triangle"></div>
</body>
方法五: transform: skew();
<style>
.triangle{
width: 150px;
height: 150px;
background-color: yellow;
transform: skew(0deg,45deg);
}
<body>
<div class="triangle"></div>
</body>
方法六: background: conic-gradient()
<style>
.triangle{
width: 150px;
height: 150px;
//从圆心为(0 0) 位置,起点在45°,从透明45°到90°,从0°开始绘制黄色
background: conic-gradient(from 45deg at 0 0,transparent 0,transparent 90deg,yellow 0deg);
}
</style>
</head>
<body>
<div class="triangle"></div>
</body>