之前博客里写过一篇关于CSS绘制各种形状的文章,当时也是边看书编写的,看到这次读书笔记第3节又看到如何画三角形的的技巧,我们索性就回顾一下。
怎么快速想起来三角形的css,首先就要想起那个4个长梯形围成的正方形:
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>三角形与聊天气泡框</title> <style> .container{ padding: 50px; } .triangle-origin{ width: 100px; height: 100px; background: salmon; border-top:100px solid lightblue; border-left:100px solid lightgreen; border-bottom: 100px solid lightblue; border-right: 100px solid lightgreen; } </style> </head> <body> <div class="container"> <div class="wrapper"> <div class="triangle-origin"> </div> </div> </div> </body>
然后我们自然会想到把中间的小方块去掉(宽度变成0)是不是就变成4个三角形头对头了呢?
我们只想要一个,那如果把上左右的border都去掉是什么样子?发现把左右上边框去掉,整个图形都不见了,为什么会这样呢?边框都在,则css会自动权重为1,所以虽然没有中间的div,大家相互依托,
起码有立足之处,其它边框删掉,中间div也没有,下边框也就不存在了,爱信不信,仅供参考。
所以可以试着保留相邻的边框,只删上边框:
发现竟然可行,其他两边的我们通过透明度把它隐藏掉就可以了,背景色也一起隐藏掉;
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>三角形与聊天气泡框</title> <style> .container{ padding: 50px; } .triangle-origin{ width: 0; height: 0; background: salmon; border-left:100px solid rgba(0,0,0,0); border-bottom: 100px solid rgba(0,0,0,0); border-right: 100px solid lightgreen; } </style> </head> <body> <div class="container"> <div class="wrapper"> <div class="triangle-origin"> </div> </div> </div> </body>
大功告成,如果你完整看到这里,什么上下左右正斜的三角都不是问题,改改各边长宽总有你想要的效果。
知道三角形的画法,这个就不是事了,直接上代码。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>三角形与聊天气泡框</title> <style> .container{ padding: 50px; } .wrapper{ margin-bottom: 40px; } .triangle-origin{ /* width: 100px; height: 100px; */ width: 0; height: 0; background-color: transparent; /* border-top:100px solid lightblue; */ border-left:100px solid transparent; border-right: 100px solid transparent; border-bottom: 100px solid lightblue; } .msg{ width: 300px; height: 80px; line-height: 80px; border: 1px solid lightgreen; position: relative; padding-left: 20px; border-radius: 10px; filter: drop-shadow(0 0 2px #999); background: #fff; } .msg::before{ content: ''; position: absolute; left: -10px; top: 44px; border-top: 6px solid transparent; border-bottom: 6px solid transparent; border-right:10px solid lightgreen; } .msg::after{ content: ''; position: absolute; left: -8px; top: 44px; border-top: 6px solid transparent; border-bottom: 6px solid transparent; border-right:10px solid #fff; } </style> </head> <body> <div class="container"> <div class="wrapper"> <div class="triangle-origin"> </div> </div> <div class="wrapper"> <div class="msg"> 要分清伪元素和伪类哦! </div> </div> </div> </body> </html>
下次就写伪元素和伪类吧,就这么愉快地决定了。