1. 背景
很多设计稿都会出现三角形,或者带有三角的对话框,三角形的图案一般出现在展开收起这类的场景,带有三角的对话框一般出现在对于文字的说明,某些操作等场景
2. 实现
实现三角形或者三角对话框有两种,一种简单点的,直接用图片😉,第二种用css纯手工实现
3. CSS 实现过程-->实心三角形
3.1 声明一个div块50px*50px,给这个div块加上border 50px得到
然后把宽高设置为0得到
然后我们把上边框宽度设置为0,得到
根据css属性border-color是用于设置元素四个边框颜色的快捷属性:border-top-color, border-right-color, border-bottom-color, [border-left-color](https://developer.mozilla.org/zh-CN/docs/Web/CSS/border-left-color)
分别把右边框和左边框设置为透明色:border-color: transparent transparent gold transparent;
得到:
完整代码为:
.test {width: 0;height: 0;border: solid;border-width: 0 50px 50px;border-color: transparent transparent gold transparent;margin: 400px;}
4. 带边框的空心三角形
4.1 思路
用一大一小div重叠在一起,在把小块的border颜色换成白色
4.2 实现代码
.border-up { width: 0; height: 0; border-style: solid; border-width: 0 50px 50px; border-color: transparent transparent #d9534f; position: relative; margin: 600px; } .border-up:after { content: ''; border-style: solid; border-width: 0 47px 47px; border-color: transparent transparent white; position: absolute; top: 2px; left: -47px; z-index: 1; }
得到的图形为:
把上面小div的top:2px改成3px得到
在加上一个before实现一个向上的箭头:
.border-up::before { content: ''; position: absolute; width: 3px; height: 60px; background: #d9534f; left: 0; right: 0; top: 40px; margin: auto; display: block; z-index: 2; }
5. 带三角的对话框
5.1 思路
5.2 代码
代码我就不写了,我这里附上由一个白色背景的正方块旋转得到的带有阴影的三角形代码:
.box_main { position: relative; margin: 100px; width: 100px; height: 50px; } .content { width: 100px; height: 50px; line-height: 50px; text-align: center; font-size: 16px; background: #ccc; border-radius: 10px; } .dialogue { position: absolute; z-index: 1; top: 38px; left: 50%; margin-left: -54.5px; box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.2); text-align: center; padding: 7px 0; box-sizing: border-box; border-radius: 5px; width: 109px; list-style-type: none; background: #fff; } .dialogue li { padding: 11px 0; color: #333; font-size: 14px; white-space: nowrap; border: 0; outline: 0; line-height: 1; background: #fff; } .dialogue::after { content: ""; position: absolute; width: 12px; height: 12px; top: -6px; right: 0; left: 0; margin: auto; background: #fff; transform: rotate(45deg); box-shadow: -2px -2px 5px -1px rgba(0, 0, 0, 0.2); }
效果图