原理
使用css画三角形主要是使用边框来画。由于css每个边的边框都可以自己定义,而且当盒子内容和内边距宽高都为0时,边框会把一个盒子四等分,最后集中于中心点。所以,只要运用好表示透明边框的transparent属性,就可以画出想要的三角形。
1、各个边框设置后的效果
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div{
width: 0;
height: 0;
border-top: 100px solid red;
border-left: 100px solid gold;
border-right: 100px solid green;
border-bottom: 100px solid black;
}
</style>
</head>
<body>
<div class="div"></div>
</body>
</html>
2、设置左上为透明后的效果
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div{
width: 0;
height: 0;
border-top: 100px solid transparent;
border-left: 100px solid transparent;
border-right: 100px solid green;
border-bottom: 100px solid black;
}
</style>
</head>
<body>
<div class="div"></div>
</body>
</html>
3、有宽高的效果
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.div{
width: 20px;
height: 20px;
border-top: 100px solid red;
border-left: 100px solid gold;
border-right: 100px solid green;
border-bottom: 100px solid black;
}
</style>
</head>
<body>
<div class="div"></div>
</body>
</html>