要想了解如何用css实现一个三角形,首先要知道三角形必须用border来实现
首先来看一段代码
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
div{
width: 0;
height: 0;
border-left: 30px solid red;
border-right:30px solid yellow;
border-top: 30px solid blue;
border-bottom: 30px solid black;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
这里是效果图,在这里我们可以发现,当div不存在内容时,如果存在边距(border),那么内容就是由边距组成的,左边的边距代表红色的三角形,同理,右边的边距代表的是黄色的三角形。
如果我们只需要一个等腰直角三角形,只需要给其他三边的颜色改为透明即可。
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
div{
width: 0;
height: 0;
border-left: 30px solid transparent;
border-right:30px solid transparent;
border-top: 30px solid transparent;
border-bottom: 30px solid black;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
这样就是一个黑色的三角形了。
如果有一条边距与其他边距不相同的话
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
div{
width: 0;
height: 0;
border-left: 30px solid red;
border-right:30px solid yellow;
border-top: 30px solid blue;
border-bottom: 15px solid black;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
以下是效果图,底部边距是顶部边距的一半,比例是1:2.我们发现垂直方向,底部三角形和顶部三角形他们的比例也是1:2,纵向三角形(左边和右边)的水平距离的平分点正好是横向三角形(上边和下边)的交叉点
现在加大难度,让2条边的值均不等
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
div{
width: 0;
height: 0;
border-left: 30px solid red;
border-right:15px solid yellow;
border-top: 30px solid blue;
border-bottom: 15px solid black;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
这里是效果图,我们发现水平距离的比例同样是1:2,水平距离的交叉点也正好是纵向三角形的交叉点。这样一步步推下去,同时使用border-left|right|top|bottom-color:transparent;我们就可以实现各种各样的三角形了。
tip: border-left+border-right的值等于 三角形水平方向的总长度 border-top加border-bottom的值等于三角形垂直方向的总长度